姬長信(Redy)

如何使用springboot应用程序绕过或跳过Mockit…


我使用springboot appllication和mockito进行测试.以下是一些文件和代码示例.
public class CustomerInfoFilter extends GenericFilterBean
{

    @Override
    public void doFilter (ServletRequest request,
                          ServletResponse response,
                          FilterChain chain)
        throws IOException,
        ServletException
    {
        Customer customer = (Customer)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // some more logic 

        // call next filter in the filter chain
        chain.doFilter(request, response);
     }
}

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

    @Autowired
    public void configAuthentication (AuthenticationManagerBuilder auth) throws Exception
    {
        auth.jdbcAuthentication()........... some logic
    }

    protected void configure (HttpSecurity http) throws Exception
    {
        http.addFilterAfter(new CustomerInfoFilter(customerInfoDao), BasicAuthenticationFilter.class);
        // Some logic
    }
}

下面是用Mockito测试编写的一段代码:

@Test
public void verifyCustomerInfoUnauthorized () throws Exception
{
    mockMvc.perform(MockMvcRequestBuilders.post("/customer").contentType(
    MediaType.APPLICATION_JSON).content("{}").accept(MediaType.APPLICATION_JSON)).andExpect(
            status().isUnauthorized()).andExpect(status().is(401));
}

>现在您可以在SecurityConfig类中看到,CustomerInfoFilter将在BasicAuthenticationFilter之后调用.
>因为编写测试的方式失败,因为它没有发送任何身份验证详细信息.
>和一段代码:客户客户=(客户)SecurityContextHolder.getContext().getAuthentication().getPrincipal();使用NullpointerException失败,因为我们没有在测试中传递身份验证详细信息,getAuthenticaiton()将返回null.

问题:如何在mockito中跳过此自定义过滤器.换句话说,如何在测试期间禁用此自定义过滤器.或任何其他解决方法或技巧.?

对不起,我是春天和mockito的新手:)任何帮助将不胜感激.