Zaccus
Zaccus

Reputation: 353

Spring Boot 2.1 : Not loading property from application-test.yml

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

Upvotes: 10

Views: 13295

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40058

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

Upvotes: 13

Related Questions