【发布时间】:2014-07-04 23:03:53
【问题描述】:
我有以下控制器,我想对其进行 Junit 测试,
@RequestMapping(value = "/path", method = RequestMethod.Get)
public String getMyPath(HttpServletRequest request, Model model) {
Principal principal = request.getUserPrincipal();
if (principal != null) {
model.addAttribute("username", principal.getName());
}
return "view";
}
JUnit 方法如下所示:
@Test
public void testGetMyPath() throws Exception {
when(principalMock.getName()).thenReturn("someName");
this.mockMvc.perform(get("/path")).andExpect(status().isOk());
}
principalMock 是这样声明的:
@Mock
private Principal principalMock;
问题是我在主体上调用 getName() 方法时在这一行得到 NullPointerException。
model.addAttribute("username", principal.getName());
【问题讨论】:
-
为什么在请求映射为 GET 时在测试中发布?
-
我编辑了问题,
标签: spring spring-mvc controller mocking spring-mvc-test