4

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.

TechCrunch
  • 2,356
  • 3
  • 39
  • 73
  • I am having a similar issue, have you had any luck solving this? Or have you figured out another/proper way to do it? – Ordiel Feb 23 '18 at 20:46
  • Did you try adding `@RunWith` on the class? What's the content of `AbstractTestNGSpringContextTests`? – Dherik Mar 27 '18 at 14:09

1 Answers1

1

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