Java 重写单个Spring启动测试的属性
考虑以下示例:Java 重写单个Spring启动测试的属性,java,spring,spring-boot,Java,Spring,Spring Boot,考虑以下示例: @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = { "some.property=valueA" }) public class ServiceTest { @Test public void testA() { ... } @Test
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {
"some.property=valueA"
})
public class ServiceTest {
@Test
public void testA() { ... }
@Test
public void testB() { ... }
@Test
public void testC() { ... }
}
我正在使用
springbootest
annotation的properties
属性设置该测试套件中所有测试的some.property
属性值。现在,我想为其中一个测试设置此属性的另一个值(比如testC
),而不影响其他测试。我怎样才能做到这一点?我已经阅读了,但没有找到任何与我的用例相匹配的内容。在Spring上下文加载期间,Spring将对您的属性进行评估。因此,您无法在容器启动后更改它们 作为解决方法,您可以将这些方法拆分为多个类,从而创建它们自己的Spring上下文。 但是要小心,因为这可能是一个坏主意,因为测试的执行应该是快速的 更好的方法是在被测试的类中有一个setter来注入
some.property
值,并在测试中使用此方法以编程方式更改该值
private String someProperty;
@Value("${some.property}")
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
如果您正在使用
@ConfigurationProperties
,这只是另一种解决方案:
@Test
void do_stuff(@Autowired MyProperties properties){
properties.setSomething(...);
...
}
更新 可能与弹簧5.2.5和弹簧护套2.2.6配合使用
@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("some.property", () -> "valueA");
}
如果只需要配置几个属性,可以使用新的@DynamicPropertySource注释。我认为如果这个方法先运行,这个类中的所有其他测试也会改变。我想是的,但是我们也可以将属性自动连接到setup方法中,并在那里设置默认值