Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring WithMockUser annotation with TestNG

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.

like image 824
TechCrunch Avatar asked May 23 '17 05:05

TechCrunch


Video Answer


1 Answers

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

like image 131
L3uchtkug3l Avatar answered Oct 08 '22 16:10

L3uchtkug3l