2
我有以下控制器和我想打一個JUnit測試就可以了,春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;
問題是我得到NullPointerException在這一行調用getName()方法在pri上ncipal。
model.addAttribute("username", principal.getName());
爲什麼是
MockHttpServletRequest
您在請求映射爲GET時在測試中發佈? – geoand我編輯了問題, – Jones
好的,我會檢查它! – geoand