I am using Spring Boot for my web app and TestNG for unit testing. Following is the unit test I'm trying
@ContextConfiguration
public class AuthorizerTest extends AbstractTestNGSpringContextTests {
@InjectMocks
private Authorizer authorizer = new Authorizer();
@Mock
private PermissionRuleRepository permissionRuleRepository;
@BeforeMethod
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
@WithMockUser
public void testCheckPermission() throws Exception {
try {
authorizer.checkPermission(null, PermissionLevel.Type.ACCOUNT_OTHER);
fail();
} catch (AccessDeniedException ade) {
//
}
}
}
authorizer.checkPermission
internally using SecurityContext
to get the current username. But on debugging, the authentication
object is null
. Not sure why it is not getting populated when using WithMockUser
.
You can try to add the following annotation to your test class. This worked for me.
@TestExecutionListeners({WithSecurityContextTestExecutionListener.class})
An example can be found here: https://github.com/sbrannen/spring-events/blob/master/src/test/java/com/sambrannen/spring/events/SimpleScenarioTestNgTests.java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With