S
S
Skoleev2021-08-18 16:42:09
Java
Skoleev, 2021-08-18 16:42:09

During tests bootstrap Spring Security and require userService, how to turn off Spring security in tests or get around this problem?

I have a simple test, as we can see, excludeAutoConfiguration and addfilters have already been added (but there is no difference). If I don't mock the UserService bean, I get this error.
Parameter 0 of constructor in com..restaurant.security.SecurityConfig required a bean of type 'com..restaurant.security.UserService' that could not be found.

@WebMvcTest(value = UserRestaurantController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class)
@AutoConfigureMockMvc(addFilters = false)
class UserRestaurantControllerTest {

    @Autowired
    MockMvc mockMvc;
    @Autowired
    ObjectMapper mapper;

    @MockBean // Если тут не будет mockbean, то выдаст ошибку выше
    RestaurantService restaurantService;



    RestaurantResponseDTO restaurantDominos = new RestaurantResponseDTO(1, "Dominos Pizza", "Басейна, 17", 3);
    RestaurantResponseDTO restaurantMamamia = new RestaurantResponseDTO(2, "Mamamia", "проспект Победы, 9Б", 14);
    RestaurantResponseDTO restaurantAndriano = new RestaurantResponseDTO(3, "Adriano's pizza", "Глибочицкая, 33/37", 2);

    @Test
     void shouldFind3Restaurants_whenGet() throws Exception {
        List<RestaurantResponseDTO> restaurantsResponse = new ArrayList(Arrays.asList(
                restaurantDominos, restaurantMamamia, restaurantAndriano));

        Mockito.when(restaurantService.getAll()).thenReturn(restaurantsResponse);

        mockMvc.perform(get("/restaurant")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(3)))
                .andExpect(jsonPath("$[2].name", is("Adriano's pizza")));
    }

Here is my ISP

@Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
        daoProvider.setPasswordEncoder(passwordEncoder());
        daoProvider.setUserDetailsService(userService); // Вот и бин, который ему нужен
        return daoProvider;
    }


I don't even know what to do anymore.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question