I'm writing a few unit tests for a Spring application that can be run with two different configurations. The two different configurations are given by two application.properties
file. I need to write tests twice for each class, since I need to verify that changes that work with a configuration don't impact the other one.
For this reason I created two files in the directory:
src/test/resources/application-configA.properties
src/test/resources/application-configB.properties
Then I tried to load them using two different values of @TestPropertySource
:
@SpringBootTest
@TestPropertySource(locations = "classpath:application-configA.properties")
class FooTest {
@InjectMock
Foo foo;
@Mock
ExternalDao dao;
// perform test
}
And the Foo
class is this one:
@Service
public class Foo {
@Autowired
private External dao;
methodToTest() {
Properties.getExampleProperty();
this.dao.doSomething(); // this needs to be mocked!
}
}
While the class Properties
is:
@Component
public class Properties {
private static String example;
@Value("${example:something}")
public void setExampleProperty(String _example) {
example = _example;
}
public static String getExampleProperty() {
return example;
}
}
The problem is that Properties.getExampleProperty()
always returns null during the test, while it contains the correct value in the normal execution.
I've tried:
- Setting a default ("something" above)
- Setting a value in
application.properties
- Setting a value in
application-configA.properties
of /main - Setting a value in
application-configA.properties
of /test - Setting a inline value in @TestPropertySource
Nothing of these worked.
I've read this question's answers, but looks like something different and they did not help me