I have the following controller and I want to make a Junit Test on it,
@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";
}
The JUnit Method looks as follows:
@Test
public void testGetMyPath() throws Exception {
when(principalMock.getName()).thenReturn("someName");
this.mockMvc.perform(get("/path")).andExpect(status().isOk());
}
principalMock is declared like this:
@Mock
private Principal principalMock;
The problem is that I get NullPointerException at this line on calling getName() method on principal.
model.addAttribute("username", principal.getName());