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

前端 未结 10 508
野趣味
野趣味 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:46

    extending Liam's answer

    you can add spring.config.additional-location=classpath:application-overrides.yaml property so config from default location will be merged with the additional config provided:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @TestPropertySource(properties = {
      "spring.config.additional-location=classpath:testcases/test-case-properties.yaml",
    })
    public class SpecificTestCaseIntegrationTest {
    
    0 讨论(0)
  • 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]

    0 讨论(0)
  • 2021-01-31 14:53

    adding to Liam's answer, an alternative will be:

    @TestPropertySource(locations = { "classpath:application.yaml" })
    

    the key difference here is that the test will fail with a file not found exception if application.yaml is not in your /test/resources directory

    0 讨论(0)
  • 2021-01-31 14:59

    In my case I was trying to test a library without a @SpringBootApp declared in the regular app classpath, but I do have one in my test context. After debugging my way through the Spring Boot initialization process, I discovered that Spring Boot's YamlPropertySourceLoader (as of 1.5.2.RELEASE) will not load YAML properties unless org.yaml.snakeyaml.Yaml is on the classpath. The solution for me was to add snakeyaml as a test dependency in my POM:

        <dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.19</version>
            <scope>test</scope>
        </dependency>
    
    0 讨论(0)
提交回复
热议问题