Reputation:
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());
Upvotes: 2
Views: 1002
Reputation: 64099
Your mocking of Principal has absolutely no effect, since it cannot come into play anywhere (the controller is not using any injected dependency to produce the principal, but it uses the HttpServletRequest).
You need to change your test to something like the following:
this.mockMvc.perform(get("/path").principal(principalMock)).andExpect(status().isOk());
This will work because the mock principal will be passed to the MockHttpServletRequest
that will actually be passed to the controller method
Upvotes: 0