如何测试将 Spring 云配置服务器的属性作为依赖项注入其中的服务?
- -我是否只是在测试期间使用 new 关键字创建自己的属性?(新的示例属性(((
- 还是我必须使用 spring 并创建某种测试属性并使用配置文件来告诉要使用哪些属性?
- 还是我应该让 spring 在测试期间调用 spring 云配置服务器?
我的服务如下所示:
@Service
class Testing {
private final ExampleProperties exampleProperties
Testing(ExampleProperties exampleProperties) {
this.exampleProperties = exampleProperties
}
String methodIWantToTest() {
return exampleProperties.test.greeting + ' bla!'
}
}
我的项目在启动期间调用 spring 云配置服务器以获取属性,这是通过在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注释在测试期间伪造属性:
@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" })
public class MyIntegrationTests {
// class body...
}
对于单元测试,只需简单地模拟属性并使用 Mockito 方法,当(mockedProperties.getProperty(eq("propertyName"((.thenReturn("mockPropertyValue"( 就可以了。
对于集成测试,所有 Spring 上下文都应该启动并作为常规应用程序工作,在这种情况下,您不需要模拟您的属性。
另一种选择是使用 SpringBootTest 注解的属性属性:
@SpringBootTest(properties = {"timezone=GMT", "port=4242"})