Should I fake Spring Cloud Config server properties during tests?

How can I check a service that has properties from spring cloud config server injected into it as a dependency?

  • -Do I just create my own properties while testing using a new keyword? (new ExampleProperties ())
  • Or do I have to use spring and create some kind of test properties and use profiles to specify which properties to use?
  • Or do I just let spring call <spring cloud config server during testing?

My service looks like this:

@Service
class Testing {

    private final ExampleProperties exampleProperties

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

    String methodIWantToTest() {
        return exampleProperties.test.greeting + ' bla!'
    }
}

      

My project makes a call to the spring cloud config server at startup time to get properties, this is resolved with the following in bootstrap.properties

:

spring.cloud.config.uri=http://12.345.67.89:8888

      

I have a configuration that looks like this:

@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
    }
}

      

The properties file looks like this:

foo=hello
bar=15

test.greeting=Hello world!

      

+3


source to share


3 answers


You can use the @ TestPropertySource annotation to fake properties during a test:



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

      

+7


source


For Unit test, just select mock Properties and use Mockito methods when (mockedProperties.getProperty (eq ("propertyName")). ThenReturn ("mockPropertyValue") and you should be fine.



For the integration test, all the Spring context must be enabled and work like a normal application, in this case you don't need to mock your properties.

+2


source


Another option is to use the SpringBootTest annotation properties attribute:

@SpringBootTest(properties = {"timezone=GMT", "port=4242"})

      

+1


source







All Articles