How to use Spring annotation WithMockUser with TestNG

I am using Spring Boot for my web application and TestNG for unit testing. Below is an example unit test

@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

using SecurityContext

to get the current username. But when debugging, the authentication

null

. Not sure why it doesn't populate when used WithMockUser

.

+3


source to share





All Articles