I am using springboot appllication and mockito for testing. So below are some files and code samples.
public class CustomerInfoFilter extends GenericFilterBe
@Mock
SecurityContext context;
@Mock
Authentication auth;
@Mock
Principal principal;
@Test
public void verifyCustomerInfoUnauthorized () throws Exception
{
when(context.getAuthentication()).thenReturn(auth);
when(context.getAuthentication().getPrincipal()).thenReturn(principal);
SecurityContextHolder.setContext(context);
mockMvc.perform(MockMvcRequestBuilders.post("/customer").principal().contentType(
MediaType.APPLICATION_JSON).content("{}").accept(MediaType.APPLICATION_JSON)).andExpect(
status().isUnauthorized()).andExpect(status().is(401));
}
You can do something like above or set the mocks directly in the test method. Either way it should do the trick. The most important piece is the .setContext()
piece. That's where your null pointer is coming from.
I find this is the cleanest way to go about it.