The most recent patch for this version is 26.2.1.  Learn more

Skip to main content

Write tests

Once you have captured your requirements and defined your attributes, write the tests. A test sends an access request with attribute values to your policies and checks the decision. Write one or more tests for each requirement, for example for the cases that must be permitted and those that must not, and give each test a display name with the requirement it verifies.

  1. Delete the example tests of the APD distribution in src/test/java/, together with the example policies and attributes.

  2. Create a test class in your test package, for example src/test/java/com/acme/MyTest.java. The following test uses the attributes from Create the dictionary:

    src/test/java/com/acme/MyTest.java
    package com.acme;

    import apd.Dictionary;
    import com.axiomatics.cr.alfa.test.junit.AlfaExtension;
    import com.axiomatics.cr.alfa.test.junit.TestResponse;
    import org.junit.jupiter.api.DisplayName;
    import org.junit.jupiter.api.Test;
    import org.junit.jupiter.api.extension.RegisterExtension;

    import static com.axiomatics.cr.alfa.test.junit.matchers.AlfaMatchers.permit;
    import static org.hamcrest.CoreMatchers.is;
    import static org.hamcrest.MatcherAssert.assertThat;

    public class MyTest {

    @RegisterExtension
    public AlfaExtension alfa = new AlfaExtension();

    @Test
    @DisplayName("REQ-ABAC-1: Should permit a Consultant to access resource in same location")
    public void shouldPermitConsultantInSameLocation() {
    TestResponse result = alfa.newTestRequest()
    .with(Dictionary.ACME_USER_ROLE, "consultant")
    .with(Dictionary.ACME_USER_LOCATION, "london")
    .with(Dictionary.ACME_RESOURCE_LOCATION, "london")
    .evaluate();

    assertThat(result, is(permit()));
    }
    }

    AlfaExtension compiles your policies and evaluates each test request.

    note

    The tests evaluate the requests with the main policy. Set it to your top-level policy with mainpolicy in the alfa { } section of build.gradle, for example mainpolicy "acme.Main".

    Dictionary contains a constant for each attribute in attributes.yaml. It is generated by generateJavaDictionaryFromYaml, so generate it before you compile the test. With the constants, the compiler finds a mistyped attribute name. You can also write the name as a string, for example .with("acme.user.role", "consultant").

  3. Run the test with ./gradlew test, or from your IDE. It fails, because no policy permits the request yet: the test states a requirement that the policies do not implement. The test report is in build/reports/tests/test/index.html.

Next, write the policy that makes the test pass: Write ALFA policies.

tip

For more about tests, such as other assertions, tests of attribute connectors, and tests against a running ADS, see Test policies in depth.