java – @TestPropertySource在Spring 1.2.6中使用AnnotationConfigContextLoader进行JUnit测试不起作用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – @TestPropertySource在Spring 1.2.6中使用AnnotationConfigContextLoader进行JUnit测试不起作用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2343字,纯文字阅读大概需要4分钟。
内容图文
看起来我在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类.
并在单元测试中使用它.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class PropertyTests {
@Value("${elastic.index}")
String index;
@Configuration
@Import({PropertyTestConfiguration.class})
static class ContextConfiguration {
}
}
内容总结
以上是互联网集市为您收集整理的java – @TestPropertySource在Spring 1.2.6中使用AnnotationConfigContextLoader进行JUnit测试不起作用全部内容,希望文章能够帮你解决java – @TestPropertySource在Spring 1.2.6中使用AnnotationConfigContextLoader进行JUnit测试不起作用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。