【发布时间】:2019-05-15 10:34:04
【问题描述】:
我正在使用 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 之后调用。
- 因为编写测试的方式失败了,因为它没有发送任何身份验证详细信息。
- 还有一段代码:
Customer customer =(Customer)SecurityContextHolder.getContext().getAuthentication().getPrincipal();因 NullpointerException 而失败,因为我们没有在测试中传递身份验证详细信息,getAuthenticaiton() 将返回 null。
问题:如何在 mockito 中跳过这个自定义过滤器。?换句话说,如何仅在测试期间禁用此自定义过滤器。?
或任何其他解决方法或技巧。?
对不起,我是 spring 和 mockito 的新手 :) 任何帮助将不胜感激。
【问题讨论】:
-
你能告诉我们你如何引导你的测试吗?
-
@Haim Raman 对不起,我没明白你的意思?....我正在运行 Junit 测试。
-
这是一个普通的 Junit 还是 @SpringBootTest
-
@HaimRaman 。它标记为
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest -
你如何设置你的 mockmvc
标签: java spring spring-boot testing mockito