javaspringspring-bootspring-securityspring-security-rest

Spring-boot WebMvcTest, why am i getting this NullPointer when i provide a mocked UserDetailsService?


I am trying to create some @WebMvcTest cases in Spring boot. I have a controller under test and i am trying to use @WithUserDetails so that i can test the Authentication object that gets passed to my controller method as a parameter.

I have a custom UserDetails extension named EmployeeDetails.

I mock my UserDetailsService with @MockBean and i make it return a custom EmployeeDetails object using given(userDetailsService.loadUserByUsername(anyString())).willReturn(new EmployeeDetails(employee, account));

However, when i run the test i get the following error:

java.lang.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(setupBefore=TEST_METHOD, userDetailsServiceBeanName=userDetailsService, value=someemail@email.com)

    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:126)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:96)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.beforeTestMethod(WithSecurityContextTestExecutionListener.java:62)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.lang.NullPointerException
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:63)
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:44)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:123)
    ... 23 more

What is causing this? I don't understand. I am under the impression that the mocked UserDetailsService should return the object that i provide in the given call. Why am i getting the NullPointer? Can anyone point me in the right direction?

Thanks!

This is my test case:

@RunWith(SpringRunner.class)
@WebMvcTest(PDPController.class)
@AutoConfigureMockMvc(addFilters = false)
public class PDPControllerTests {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private PDPService pdpService;

    @MockBean(name = "userDetailsService")
    private MyUserDetailsService userDetailsService;
    
    //..
    
    @Test
    @WithUserDetails(value = "someemail@email.com", userDetailsServiceBeanName = "userDetailsService")
    public void testSaveBackground_returns_result_from_service() throws Exception {
        PersonalDevelopmentPlan pdp = new PersonalDevelopmentPlan();
        pdp.setEmployee(EMPLOYEE_ID);
        Account account = new Account();
        Employee employee = new Employee();

        given(pdpService.saveBackground(eq(EMPLOYEE_ID), any(), anyInt())).willReturn(pdp);
        given(userDetailsService.loadUserByUsername(anyString())).willReturn(new EmployeeDetails(employee, account));

        mvc.perform(patch(URL_WITH_ID + "/background").secure(true)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(pdp)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.employee", Matchers.is(EMPLOYEE_ID)));
    }
    
} 

Solution

  •     @PostConstruct
        public void setup() {
            Account account = new Account();
            Employee employee = new Employee();
            given(userDetailsService.loadUserByUsername(anyString()))
                 .willReturn(new EmployeeDetails(employee, account));
        }
    
       given(userDetailsService.loadUserByUsername(anyString()))
                 .willReturn(new EmployeeDetails(employee, account));