在每个春季启动 @Test 上覆盖单个 @Configuration 类 [英] Override a single @Configuration class on every spring boot @Test
问题描述
在我的 Spring Boot 应用程序中,我只想用测试配置覆盖我的 @Configuration
类之一(特别是我的 @EnableAuthorizationServer
@Configuration
class),在我所有的测试中.
On my spring boot application I want to override just one of my @Configuration
classes with a test configuration (in particular my @EnableAuthorizationServer
@Configuration
class), on all of my tests.
到目前为止spring boot 测试功能和spring 集成测试功能没有直接的解决方案浮出水面:
So far after an overview of spring boot testing features and spring integration testing features no straightforward solution has surfaced:
@TestConfiguration
:用于扩展,而不是覆盖;@ContextConfiguration(classes=… )
和@SpringApplicationConfiguration(classes =… )
让我覆盖整个配置,而不仅仅是一个类;- 建议使用
@Test
内部的@Configuration
类来覆盖默认配置,但未提供示例;
@TestConfiguration
: It's for extending, not overriding;@ContextConfiguration(classes=…)
and@SpringApplicationConfiguration(classes =…)
let me override the whole config, not just the one class;- An inner
@Configuration
class inside a@Test
is suggested to override the default configuration, but no example is provided;
有什么建议吗?
推荐答案
内测配置
用于测试的内部 @Configuration 示例:
Example of an inner @Configuration for your test:
@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")
激活配置文件.查看完整代码:
If you wish to reuse the Test Configuration for multiple tests, you may define a standalone Configuration class with a Spring Profile @Profile("test")
. Then, have your test class activate the profile with @ActiveProfiles("test")
. See complete code:
@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();
}
}
@Primary
bean定义上的@Primary
注解是为了确保在发现多个时优先使用这个.
The @Primary
annotation on the bean definition is to ensure that this one will have priority if more than one are found.
这篇关于在每个春季启动 @Test 上覆盖单个 @Configuration 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!