How to use Spring WithMockUser annotation with TestNG
Asked Answered
B

1

6

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.

Bardwell answered 23/5, 2017 at 5:46 Comment(2)
I am having a similar issue, have you had any luck solving this? Or have you figured out another/proper way to do it?Heaviside
Did you try adding @RunWith on the class? What's the content of AbstractTestNGSpringContextTests?Moniliform
H
3

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

Heida answered 20/1, 2020 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.