Issue
Spring Boot allows us to replace our application.properties
files with YAML equivalents. However, I seem to hit a snag with my tests. If I annotate my TestConfiguration
(a simple Java config), it is expecting a properties file.
For example this doesn't work:
@PropertySource(value = "classpath:application-test.yml")
If I have this in my YAML file:
db:
url: jdbc:oracle:thin:@pathToMyDb
username: someUser
password: fakePassword
And I'd be leveraging those values with something like this:
@Value("${db.username}") String username
However, I end up with an error like so:
Could not resolve placeholder 'db.username' in string value "${db.username}"
How can I leverage the YAML goodness in my tests as well?
Solution
Spring-boot has a helper for this, just add
@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
at the top of your test classes or an abstract test superclass.
Edit: I wrote this answer five years ago. It doesn't work with recent versions of Spring Boot. This is what I do now (please translate the Kotlin to Java if necessary):
@TestPropertySource(locations=["classpath:application.yml"])
@ContextConfiguration(
initializers=[ConfigFileApplicationContextInitializer::class]
)
is added to the top, then
@Configuration
open class TestConfig {
@Bean
open fun propertiesResolver(): PropertySourcesPlaceholderConfigurer {
return PropertySourcesPlaceholderConfigurer()
}
}
to the context.
Answered By - Ola Sundell
Answer Checked By - Katrina (JavaFixing Volunteer)