覆盖单个弹簧引导测试的属性

2022-09-01 19:11:03

请考虑以下示例:

@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() { ... }
}

我正在使用注释的属性来设置此测试套件中所有测试的属性值。现在,我想为其中一个测试(假设)设置此属性的另一个值,而不会影响其他测试。我怎样才能做到这一点?我已经阅读了Spring Boot文档的“测试”一章,但我没有找到任何与我的用例相匹配的东西。SpringBootTestpropertiessome.propertytestC


答案 1

在 Spring 上下文加载期间,您的属性由 Spring 进行评估。
因此,在容器启动后无法更改它们。

作为解决方法,您可以将这些方法拆分为多个类,从而创建自己的Spring上下文。但要小心,因为这可能是一个坏主意,因为测试执行应该很快。

更好的方法可能是在被测类中注入值的 setter,并在测试中使用此方法以编程方式更改值。some.property

private String someProperty;

@Value("${some.property}")
public void setSomeProperty(String someProperty) {
    this.someProperty = someProperty;
}

答案 2

更新

至少可以在Spring 5.2.5和Spring Boot 2.2.6中使用

@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
    registry.add("some.property", () -> "valueA");
}

推荐