繁体   English   中英

Spring MVC测试:控制器方法参数

[英]Spring MVC Testing: Controller Method Parameters

我正在尝试为Spring MVC Web应用程序编写测试。

我已经成功配置了MockMvc对象,并且可以执行preform()操作,并且可以验证是否正在调用我的控制器方法。

我遇到的问题与将UserDetails对象传递给控制器​​方法有关。

我的控制器方法签名如下:

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

在测试期间, user为null(由于我的代码,这导致NullPointerException

这是我的测试方法:

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

所以我的问题是如何正确地将UserDetails对象传递到我的MockMvc控制器中? 其他与安全无关的对象(例如表单dto)呢?

谢谢你的帮助。

您需要像这样在单元测试中初始化安全上下文:

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

我使用以下设置:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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