How to: test programmatic authorization checks in a unit test
Unit tests are meant to test classes in isolation. Consequently, these tests also take place outside a Spring
application context. Therefore, neither the autoconfiguration of the jeap-spring-boot-security-starter nor
any declarative authorization checks have any influence on the test. However, if a method under test performs
programmatic authorization checks, a JeapAuthenticationToken must be provided for it.
Steps
- Add the test dependency
jeap-spring-boot-security-starter-testto the project (see Integration). - Mock the
JeapAuthenticationTokenfor the programmatic authorization check under test, for example with the AuthorizationMock classes —ServletSimpleAuthorizationMockorServletSemanticAuthorizationMock— storing a token created with the JeapAuthenticationTestTokenBuilder. Alternatively, plain Mockito mocks can be used for this as well.
This example shows how the JeapAuthenticationToken can be mocked for the test of a method with a
programmatic authorization check.
Related
- Testing secured REST APIs — the test-support classes used above, and the other test use cases.
- How to: test a component with a given authentication — the equivalent for integration tests that run inside a (partial) Spring application context.
- How to: disable security in a Spring Boot test — mocking the same
jeapAuthorizationbean when security should otherwise be left out of a Spring Boot test.