How to bypass or skip CustomFilter in Mockito with springboot applicaiton

后端 未结 1 1652
天涯浪人
天涯浪人 2020-12-04 03:58

I am using springboot appllication and mockito for testing. So below are some files and code samples.

public class CustomerInfoFilter extends GenericFilterBe         


        
相关标签:
1条回答
  • 2020-12-04 04:39
    @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.

    0 讨论(0)
提交回复
热议问题