在我的 Spring Boot 应用程序中,我只想在所有测试中使用测试配置覆盖我的
@Configuration
类之一(特别是我的 @EnableAuthorizationServer
@Configuration
类)。
到目前为止,在概述了spring boot测试功能和spring集成测试功能之后,还没有出现简单的解决方案:
@TestConfiguration
:用于扩展,而不是覆盖;@ContextConfiguration(classes=…)
和 @SpringApplicationConfiguration(classes =…)
让我可以覆盖整个配置,而不仅仅是一个类;@Configuration
中使用内部 @Test
类来覆盖默认配置,但未提供示例;有什么建议吗?
内部测试配置
测试的内部@Configuration示例:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SomeTest {
@Configuration
static class ContextConfiguration {
@Bean
@Primary //may omit this if this is the only SomeBean defined/visible
public SomeBean someBean () {
return new SomeBean();
}
}
@Autowired
private SomeBean someBean;
@Test
public void testMethod() {
// test
}
}
可重复使用的测试配置
如果您希望在多个测试中重用测试配置,您可以使用 Spring Profile 定义一个独立的配置类
@Profile("test")
。然后,让您的测试类使用 @ActiveProfiles("test")
激活配置文件。查看完整代码:
@RunWith(SpringRunner.class)
@SpringBootTests
@ActiveProfiles("test")
public class SomeTest {
@Autowired
private SomeBean someBean;
@Test
public void testMethod() {
// test
}
}
@Configuration
@Profile("test")
public class TestConfiguration {
@Bean
@Primary //may omit this if this is the only SomeBean defined/visible
public SomeBean someBean() {
return new SomeBean();
}
}
@小学
bean定义上的
@Primary
注释是为了确保如果找到多个bean,则该bean具有优先权。
您应该使用spring boot配置文件:
@Profile("test")
注释您的测试配置。@Profile("production")
注释您的生产配置。spring.profiles.active=production
。@Profile("test")
在测试类中设置测试配置文件。因此,当您的应用程序启动时,它将使用“生产”类,而当测试启动时,它将使用“测试”类。
如果您使用内部/嵌套
@Configuration
类,将使用它将代替应用程序的主要配置。
我最近必须创建我们的应用程序的开发版本,它应该使用开箱即用的
dev
活动配置文件运行,无需任何命令行参数。我通过将这一类添加为新条目来解决这个问题,它以编程方式设置活动配置文件:
package ...;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;
@Import(OriginalApplication.class)
public class DevelopmentApplication {
public static void main(String[] args) {
SpringApplication application =
new SpringApplication(DevelopmentApplication.class);
ConfigurableEnvironment environment = new StandardEnvironment();
environment.setActiveProfiles("dev");
application.setEnvironment(environment);
application.run(args);
}
}
请参阅 Arvind Rai 的 Spring Boot 配置文件示例了解更多详细信息。
如果您只想设置一个不同的属性,您也可以使用
@SpringBootTest(properties = {"your.property.to.overwrite=TEST"})