标签:java spring spring-boot testing mockito
我使用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()部分.这就是你的空指针来自哪里.
我发现这是最干净的方法.
标签:java,spring,spring-boot,testing,mockito 来源: https://codeday.me/bug/20190926/1820295.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。