覆盖单个Spring Boot测试的属性

时间:2018-02-01 19:58:15

标签: 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
    public void testB() { ... }

    @Test
    public void testC() { ... }
}

我正在使用SpringBootTest注释的properties属性为此测试套件中的所有测试设置some.property属性的值。现在,我想为其中一个测试设置此属性的另一个值(假设为testC)而不影响其他测试。我怎样才能做到这一点?我已经阅读了"Testing" chapter of Spring Boot docs,但我找不到任何与我的用例匹配的内容。

3 个答案:

答案 0 :(得分:4)

在Spring上下文加载期间,Spring会评估您的属性 所以你不能在容器启动后更改它们。

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

更好的方法是在被测试的类中设置一个setter some.property值并在测试中使用此方法以编程方式更改值。

private String someProperty;

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

答案 1 :(得分:0)

如果您正在使用@ConfigurationProperties,则是另一种解决方案:

@Test
void do_stuff(@Autowired MyProperties properties){
  properties.setSomething(...);
  ...
}

答案 2 :(得分:0)

更新

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

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