Spring boot, read yml properties via integration test case

后端 未结 5 1073
太阳男子
太阳男子 2020-12-16 21:08

Hi I am using Spring Boot, I want to inject the values of the .yml file in the Bean. I have written the integration test case but looks like via Integration test case it not

5条回答
  •  不思量自难忘°
    2020-12-16 21:54

    SpringApplicationConfiguration is deprecated in spring [Spring Boot v1.4.x] and removed in: [Spring Boot v1.5.x]. So, this is an updated answer.

    MyTestClass class is like:

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringRunner;
    import static org.assertj.core.api.Assertions.assertThat;
    
    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = MyConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
    public class MyTestClass {
        @Autowired
        private MyYmlProperties myYmlProperties;
    
        @Test
        public void testSpringYmlProperties() {
            assertThat(myYmlProperties.getProperty()).isNotEmpty();
        }
    }
    

    MyYmlProperties class is like:

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ConfigurationProperties(prefix = "my")
    public class MyYmlProperties {
        private String property;
        public String getProperty() { return property; }
        public void setProperty(String property) { this.property = property; }
    }
    

    My application.yml is like:

    my:
      property: Hello
    

    Finally MyConfiguration is really empty :-) you can fill it with what you want:

    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @EnableConfigurationProperties(value = MyYmlProperties.class)
    public class MyConfiguration {
    }
    

提交回复
热议问题