Я пытаюсь использовать Mockito с Spring Security, но безуспешно.
Моя безопасность настроена следующим образом:
@Configuration
@EnableWebSecurity
public class ConfiguracaoDeSeguranca extends WebSecurityConfigurerAdapter {
private static final String[] PUBLICOS = {
"/api/**",
"/h2-console/**"
};
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**",
"/configuration/**", "/swagger-ui.html", "/webjars/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.authorizeRequests()
.antMatchers(PUBLICOS).permitAll()
.anyRequest().authenticated();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
И мой класс испытаний выглядит следующим образом:
@Test
public void criarNovoClientePessoaFisica() throws Exception {
PessoaFisica mockPessoaFisica = new PessoaFisica(1L, (byte) 1L, 1L, "Rodrigo Batista", "012.668.833-80", "12346 SSPMA",
"rodrigo@bitis.com.br", new Date(), GeneroEnum.MASCULINO, EstadoCivilEnum.CASADO, new Date(), 1L, 1L);
Mockito.when(pessoaFisicaService.inserir(Mockito.any(PessoaFisica.class))).thenReturn(mockPessoaFisica);
ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
String mockPessoaFisicaJson = objectWriter.writeValueAsString(mockPessoaFisica);
this.mockMvc.perform(MockMvcRequestBuilders.post("/api/clientes/pf")
.with(SecurityMockMvcRequestPostProcessors.csrf())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(mockPessoaFisicaJson))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().json(mockPessoaFisicaJson));
}
Когда я запускаю тест, он всегда выдает следующую ошибку:
java.lang.AssertionError: Status
Ожидаемое: 200
Факт: 401