@TestPropertySource和@PropertySource不适用于JUnit

看起来我在Spring 4.1.1中使用Spring Boot 1.2.6.RELEASE做的事情根本不起作用。 我只是想访问应用程序属性并在必要时使用测试覆盖它们(不使用hack手动注入PropertySource)

这不起作用..

@TestPropertySource(properties = {"elastic.index=test_index"}) 

这也不是..

 @TestPropertySource(locations = "/classpath:document.properties") 

也不是..

 @PropertySource("classpath:/document.properties") 

完整测试案例..

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) @TestPropertySource(properties = {"elastic.index=test_index"}) public class PropertyTests { @Value("${elastic.index}") String index; @Configuration @TestPropertySource(properties = {"elastic.index=test_index"}) static class ContextConfiguration { } @Test public void wtf() { assertEquals("test_index", index); } } 

导致

 org.junit.ComparisonFailure: Expected :test_index Actual :${elastic.index} 

似乎3.x和4.x之间存在很多相互矛盾的信息,我找不到任何可行的信息。

任何见解将不胜感激。 干杯!

最好的方法(直到Spring修复这个疏忽)是一个PropertySourcesPlaceholderConfigurer ,它将引入test.properties(或任何你想要的)和@Import或扩展@Configuration

 import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.IOException; @Configuration public class PropertyTestConfiguration { @Bean public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws IOException { final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer(); ppc.setLocations(ArrayUtils.addAll( new PathMatchingResourcePatternResolver().getResources("classpath*:application.properties"), new PathMatchingResourcePatternResolver().getResources("classpath*:test.properties") ) ); return ppc; } } 

这允许您在application.properties中定义默认值并在test.properties中覆盖它们。 当然,如果您有多个方案,则可以根据需要配置PropertyTestConfiguration类。

并在unit testing中使用它。

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) public class PropertyTests { @Value("${elastic.index}") String index; @Configuration @Import({PropertyTestConfiguration.class}) static class ContextConfiguration { } } 

我使用@TestPropertySourcelocations属性来覆盖(或添加)属性。

这对我有用(春季4.2.4):

 @TestPropertySource(locations = { "classpath:test.properties", "classpath:test-override.properties" }) 

但是如下所述的重写属性没有:

 @TestPropertySource( locations = {"classpath:test.properties"}, properties = { "key=value" }) 

即使javadoc说这些属性具有最高优先级。 可能有一个bug?

更新

该错误应该在Spring启动版本1.4.0及更高版本中修复。 请参阅关闭该问题的提交 。 到目前为止,以所示方式声明的属性应该优先。

您对@Value的使用需要PropertySourcesPlaceholderConfigurer bean来解析${...}占位符。 请参阅此处接受的答案: @Value未通过Java配置的测试上下文设置

对于我@TestPropertySource(“classpath:xxxxxxxx.properties”)工作

您是否尝试过使用@PropertySource("classpath:document.properties")@PropertySource("classpath*:document.properties")