我正在尝试为我的 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)呢?
谢谢你的帮助。