如何测试具有从Spring Cloud配置服务器中注入的属性作为依赖项的服务?

  • -我是否在测试过程中使用new关键字简单地创建了自己的属性?(new ExampleProperties())
  • 还是我必须使用spring并创建某种测试属性并使用配置文件来确定要使用哪些属性?
  • 还是应该在测试期间让spring调用spring cloud config服务器?

  • 我的服务如下所示:
    @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...
    }
    

    07-28 01:20
    查看更多