1

I am trying to write tests for my Spring MVC web application.

I have successfully configured a MockMvc object and can execute preform() operations, and can verify that my controller methods are being called.

The issue I am experiencing has to do with passing in a UserDetails object to my controller methods.

My controller method signature is as follows:

@RequestMapping(method = RequestMethod.GET)
public ModelAndView ticketsLanding(
        @AuthenticationPrincipal CustomUserDetails user) {
    ...
}

During the tests, user is null (which is causing a NullPointerException due to my code.

Here is my test method:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;

@Test
public void ticketsLanding() throws Exception {
    // testUser is populated in the @Before method
    this.mockMvc.perform(
            get("/tickets").with(user(testUser))).andExpect(
            model().attributeExists("tickets"));
}

So my question is how do I properly pass a UserDetails object into my MockMvc controllers? What about other, non-security related objects such as form dtos?

Thanks for your help.

2 Answers 2

2

You need to init the security context in your unit test like so:

@Before
public void setup() {
    mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity()) 
            .build();
}
Sign up to request clarification or add additional context in comments.

Comments

1

I use the following setup:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { 
        "classpath:/spring/root-test-context.xml"})
public class UserAppTest implements InitializingBean{

    @Autowired
    WebApplicationContext wac;

    @Autowired
    private FilterChainProxy springSecurityFilterChain;

    // other test methods...

    @Override
    public void afterPropertiesSet() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac)
                .addFilters(springSecurityFilterChain)
                .build();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.