我使用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的新手:)任何帮助将不胜感激.
解决方法:
@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));
}
您可以执行类似上面的操作或直接在测试方法中设置模拟.无论哪种方式它应该做的伎俩.最重要的部分是.setContext()部分.这就是你的空指针来自哪里.
我发现这是最干净的方法.