1

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

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

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

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

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

在测试期间,user为空(这是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)呢?

谢谢你的帮助。

4

2 回答 2

2

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

@Before
public void setup() {
    mvc = MockMvcBuilders
            .webAppContextSetup(context)
            .apply(springSecurity()) 
            .build();
}
于 2015-08-25T08:52:12.823 回答
1

我使用以下设置:

@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();
    }
}
于 2015-08-25T09:00:56.190 回答