Указание @SpringBootApplication в @WebMvcTest

Использование @WebMvcTest автоматически настроит все bean-компоненты веб-слоя путем поиска класса @SpringBootConfiguration (например, @SpringBootApplication).

Если класс конфигурации находится в другом пакете и не может быть найден при сканировании, могу ли я предоставить его напрямую @WebMvcTest?

3
0
1 439
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Следующее укажет на правильный класс @SpringBootApplication:

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(controllers = {MyController.class})
@ContextConfiguration(classes = {MySpringBootApplicationClass.class})
public class MyControllerTest {
    //...
}

Если вы используете @WebMvcTest для своего теста, это означает, что вы сосредоточены в основном на тестировании слоя Spring MVC и не углубляетесь в приложение.

So this annotation can be used only when a test focuses on Spring MVC components. By default, tests annotated with @WebMvcTest will also auto-configure Spring Security and MockMvc (include support for HtmlUnit WebClient and Selenium WebDriver). For more fine-grained control of MockMVC the @AutoConfigureMockMvc annotation can be used.Typically @WebMvcTest is used in combination with @MockBean or @Import to create any collaborators required by your @Controller beans.

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {

}

Затем вы можете импортировать этот класс конфигурации, используя @import в аннотированном тестовом классе @WebMvcTest, и bean-компоненты должны быть загружены к весне.

Ссылка: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html

Другие вопросы по теме