我正在尝试为使用@RefreshScope
的应用程序编写测试。我想添加一个实际更改属性并断言应用程序正确响应的测试。我已经弄清楚如何触发刷新(在 RefreshScope
中 Autowiring 并调用 refresh(...)
),但我还没有找到修改属性的方法。如果可能的话,我想直接写入属性源(而不是必须使用文件),但我不确定在哪里查找。
更新
这是我正在寻找的示例:
public class SomeClassWithAProperty {
@Value{"my.property"}
private String myProperty;
public String getMyProperty() { ... }
}
public class SomeOtherBean {
public SomeOtherBean(SomeClassWithAProperty classWithProp) { ... }
public String getGreeting() {
return "Hello " + classWithProp.getMyProperty() + "!";
}
}
@Configuration
public class ConfigClass {
@Bean
@RefreshScope
SomeClassWithAProperty someClassWithAProperty() { ...}
@Bean
SomeOtherBean someOtherBean() {
return new SomeOtherBean(someClassWithAProperty());
}
}
public class MyAppIT {
private static final DEFAULT_MY_PROP_VALUE = "World";
@Autowired
public SomeOtherBean otherBean;
@Autowired
public RefreshScope refreshScope;
@Test
public void testRefresh() {
assertEquals("Hello World!", otherBean.getGreeting());
[DO SOMETHING HERE TO CHANGE my.property TO "Mars"]
refreshScope.refreshAll();
assertEquals("Hello Mars!", otherBean.getGreeting());
}
}
最佳答案
您可以这样做(我假设您错误地省略了示例顶部的 JUnit 注释,因此我会为您将它们添加回来):
@SpringBootTest
public class MyAppIT {
@Autowired
public ConfigurableEnvironment environment;
@Autowired
public SomeOtherBean otherBean;
@Autowired
public RefreshScope refreshScope;
@Test
public void testRefresh() {
assertEquals("Hello World!", otherBean.getGreeting());
EnvironmentTestUtils.addEnvironment(environment, "my.property=Mars");
refreshScope.refreshAll();
assertEquals("Hello Mars!", otherBean.getGreeting());
}
}
您的主类还需要一个 @SpringBootApplication
注释。
但是您并没有真正测试代码,只是测试 Spring Cloud 的刷新范围功能(已经针对此类行为进行了广泛测试)。
我很确定您也可以从刷新范围的现有测试中得到这一点。
关于java - 以编程方式更改 Spring Boot 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35341684/