次のコントローラーがあり、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());