我有以下控制器,我想对其进行 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());