Spring 未选择启动测试配置

Spring boot test configuration not being picked

我正在为我的应用程序编写集成测试,并希望为我的测试使用自定义 webmvc 配置

我的基本包中有三个 classes com.marco.nutri:

我的测试在包 br.com.marco.nutri.integration.auth:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class, WebMvcTestConfiguration.class, SecurityConfig.class})
public class ITSignup {

    //Test code

}

我在包 com.marco.nutri 中有一个测试配置 class。集成:

@TestConfiguration
@EnableWebMvc
public class WebMvcTestConfiguration extends WebMvcConfigurerAdapter {
    //Some configuration
}

但是当我 运行 我的测试时,选择 MvcConfig.class 而不是 WebMvcTestConfiguration.class

我做错了什么?

您可以使用 @Profile("test") 注释您的测试配置,使用 @Profile("production")

注释您的真实配置

并在您的属性文件中放置 属性 spring.profiles.active=production 并在您的测试 class 中放置 @Profile("test")。因此,当您的应用程序启动时,它将使用 "production" class,而当测试星时,它将使用 "test" class.

来自文档

Unlike regular @Configuration classes the use of @TestConfiguration does not prevent auto-detection of @SpringBootConfiguration.

Unlike a nested @Configuration class which would be used instead of a your application’s primary configuration, a nested @TestConfiguration class will be used in addition to your application’s primary configuration.