我正在尝试为我的 Spring MVC Web 应用程序编写测试。
我已经成功配置了一个 MockMvc
对象并且可以执行 preform()
操作,并且可以验证我的 Controller 方法是否被调用。
我遇到的问题与将 UserDetails
对象传递给我的 Controller 方法有关。
我的 Controller 方法签名如下:
@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
Controller 中?其他与安全无关的对象(例如表单 dto)呢?
感谢您的帮助。
最佳答案
您需要像这样在单元测试中初始化安全上下文:
@Before
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
关于java - Spring MVC 测试 : Controller Method Parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32199281/