Override @PropertySource with @TestPropertySource in Spring Boot

老子叫甜甜 提交于 2020-01-14 10:12:52

问题


I have my Spring Boot main class:

@SpringBootApplication
@PropertySource("file:/my/file/properties")
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
  //main method
}

I'm reading properties from an external file (using @PropertySource). Now, I have an integration test:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes= Application.class)
@WebIntegrationTest
@TestPropertySource("file:/my/test/file/properties") // <---
public class MyTest {
  //some tests
}

I need to use another external properties file, different from the indicated in @PropertySource in Application class. For that reason, I have added @TestPropertySource, but seems that this annotation is not overriding the @PropertySource.

What can I do?

Thanks in advance.


回答1:


Use it this way:

@TestPropertySource(locations = "classpath:test.properties")

and place test properties file into src/test/resources




回答2:


In Java8 you can "repeat" an Annotation like:

@PropertySource(value = "file:./src/main/resources/mydefault.properties")
@PropertySource(value = "file:./src/test/resources/override.properties", ignoreResourceNotFound = true)

This way, the latter overwrites properties from the first file if available.



来源:https://stackoverflow.com/questions/36614935/override-propertysource-with-testpropertysource-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!