How to use Spring WithMockUser annotation with TestNG

Viewed 333

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.

1 Answers
Related