Cob*_*117 2 java spring spring-cloud
我正在尝试为使用@RefreshScope
. 我想添加一个实际更改属性并断言应用程序正确响应的测试。我已经想出了如何触发刷新(自动装配RefreshScope
和调用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());
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做(我假设你错误地省略了示例顶部的 JUnit 注释,所以我会为你添加它们):
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
但是您并没有真正测试您的代码,只是测试 Spring Cloud 的刷新范围功能(已经针对此类行为进行了广泛测试)。
我很确定你也可以从现有的刷新范围测试中得到这个。
归档时间: |
|
查看次数: |
9015 次 |
最近记录: |