如何测试具有从Spring Cloud配置服务器中注入的属性作为依赖项的服务?
我的服务如下所示:
@Service
class Testing {
private final ExampleProperties exampleProperties
Testing(ExampleProperties exampleProperties) {
this.exampleProperties = exampleProperties
}
String methodIWantToTest() {
return exampleProperties.test.greeting + ' bla!'
}
}
我的项目在启动过程中调用了Spring Cloud配置服务器以获取属性,这是通过在
bootstrap.properties
上添加以下内容来启用的:spring.cloud.config.uri=http://12.345.67.89:8888
我有一个类似于以下配置的配置:
@Component
@ConfigurationProperties
class ExampleProperties {
private String foo
private int bar
private final Test test = new Test()
//getters and setters
static class Test {
private String greeting
//getters and setters
}
}
属性文件如下所示:
foo=hello
bar=15
test.greeting=Hello world!
最佳答案
您可以在测试期间使用@TestPropertySource annotation伪造属性:
@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" })
public class MyIntegrationTests {
// class body...
}