I am trying to read a property from application-test.yml during my unit test execution, but instead, the property from application-dev.yml is being read instead. I do not have a application.yml file. Appreciate the help.
AppProperties.java
@Component
@ConfigurationProperties(prefix="app")
public class AppProperties {
private String test;
public String getTest() {
return this.test;
}
public void setTest(String test) {
this.test = test;
}
}
application-dev.yml
spring:
profiles: dev
application:
name: testApplication
app:
test: 1
application-test.yml
spring:
profiles: test
application:
name: testApplication
app:
test: 2
AppServiceTest.java
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppProperties.class}, initializers= ConfigFileApplicationContextInitializer.class)
@EnableConfigurationProperties
@ActiveProfiles("test")
public class AppServiceTest{
@Autowired
AppProperties appProperties;
@Test
public void test(){
appProperties.getTest();
//This returns "1" instead of the desired "2"
}
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration.
Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.
We can use @SpringBootTest annotation which loads the yml file from src\main\java\com... hence when we execute the unit test, all of the properties are already there in the config properties class. @Data @Component @RefreshScope @ConfigurationProperties(prefix = "address. fields.
Use @SpringBootTest
annotation on unit test class
Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication. In addition to @SpringBootTest a number of other annotations are also provided for testing more specific slices of an application.
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {AppProperties.class}, initializers=
ConfigFileApplicationContextInitializer.class)
@EnableConfigurationProperties
@SpringBootTest
@ActiveProfiles("test")
public class AppServiceTest{
@Autowired
AppProperties appProperties;
@Test
public void test(){
appProperties.getTest();
//This returns "1" instead of the desired "2"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With