简体   繁体   中英

Spring MVC Testing: Controller Method Parameters

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.

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

@Before
public void setup() {
    mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity()) 
            .build();
}

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM