Doug
Doug

Reputation: 6477

Should I mock Spring Cloud Config server properties during tests?

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

  1. -Do I simply create my own properties during testing using the new keyword?(new ExampleProperties())
  2. Or do I have to use spring and create some kind of test properties and use profiles to tell which properties to use?
  3. Or should I just let spring call the spring cloud config server during testing?

My service looks like the one below:

@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 a spring cloud config server during start up to get properties, this is enabled by having the following on the bootstrap.properties:

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

I have a configuration that looks like the one below:

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

Upvotes: 6

Views: 7643

Answers (3)

luboskrnac
luboskrnac

Reputation: 24561

Another option is to use properties attribute of SpringBootTest annotation:

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

Upvotes: 3

luboskrnac
luboskrnac

Reputation: 24561

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

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

Upvotes: 12

vrudas
vrudas

Reputation: 66

For Unit test just simply mock Properties and use Mockito methods when(mockedProperties.getProperty(eq("propertyName")).thenReturn("mockPropertyValue") and it will be fine.

For Integration test all Spring context should be inited and work as regular app, in that case you dont need to mock your properties.

Upvotes: 3

Related Questions