Spring Boot properties in 'application.yml' not loading from JUnit Test

前端 未结 10 510
野趣味
野趣味 2021-01-31 13:59

What am I doing wrong? I\'m using this little standalone App which runs and finds my src/main/resources/config/application.yml. The same configuration doesn\'t work

10条回答
  •  被撕碎了的回忆
    2021-01-31 14:52

    Here's another way: [Spring Boot v1.4.x]

    @Configuration
    @ConfigurationProperties(prefix = "own")
    public class OwnSettings {
    
        private String name;
        Getter & setters...
    
    }
    

    import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @BootstrapWith(SpringBootTestContextBootstrapper.class)
    public class OwnSettingsTest {
    
      @Autowired
      private OwnSettings bean;
    
      @Test
      public void test() {
        bean.getName();
      }
    }
    

    This works ONLY if also 'application.properties' file exists.

    e.g. maven project:

    src/main/resources/application.properties [ The file can be empty but it's mandatory! ]
    src/main/resources/application.yml [here's your real config file]

提交回复
热议问题