Я использую приложение Springboot и 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 () вернет ноль.
Вопрос: Как я могу пропустить этот пользовательский фильтр в mockito.?Другими словами, как можно отключить этот пользовательский фильтр только во время тестирования .?
Или любой другой обходной путь или хитрости .?
Извините, я новичок в Spring и mockito :) любая помощь будет оценена.