在@WebMvcTest 中指定@SpringBootApplication

Specifying @SpringBootApplication in @WebMvcTest

使用@WebMvcTest 将通过查找@SpringBootConfiguration class(例如@SpringBootApplication)自动配置所有web 层bean。

如果配置class在不同的包里,扫描找不到,可以直接提供给@WebMvcTest吗?

下面会指向正确的@SpringBootApplication class:

@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 {

}

然后您可以在 @WebMvcTest 带注释的测试 class 中使用 @import 导入此配置 class,并且 spring 应该会选择 bean。

参考:https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html