我应该在测试期间模拟Spring Cloud Config服务器属性吗?

Dou*_*oug 4 java groovy unit-testing spring-boot spring-cloud-config

如何测试具有spring cloud配置服务器属性的服务作为依赖项注入其中?

  1. - 我在测试期间使用new关键字创建自己的属性吗?(new ExampleProperties())
  2. 或者我是否必须使用spring并创建某种测试属性并使用配置文件来判断要使用哪些属性?
  3. 或者我应该在测试期间让spring调用spring cloud配置服务器?

我的服务如下所示:

@Service
class Testing {

    private final ExampleProperties exampleProperties

    Testing(ExampleProperties exampleProperties) {
        this.exampleProperties = exampleProperties
    }

    String methodIWantToTest() {
        return exampleProperties.test.greeting + ' bla!'
    }
}
Run Code Online (Sandbox Code Playgroud)

我的项目在启动期间调用spring cloud配置服务器来获取属性,这可以通过以下方式启用bootstrap.properties:

spring.cloud.config.uri=http://12.345.67.89:8888
Run Code Online (Sandbox Code Playgroud)

我有一个如下所示的配置:

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

属性文件如下所示:

foo=hello
bar=15

test.greeting=Hello world!
Run Code Online (Sandbox Code Playgroud)

lub*_*nac 10

您可以使用@TestPropertySource批注在测试期间伪造属性:

@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" })
public class MyIntegrationTests {
    // class body...
}
Run Code Online (Sandbox Code Playgroud)