use*_*141 19 java junit spring spring-junit
我有一个jUnit测试,它有自己的属性文件(application-test.properties)和它的spring配置文件(application-core-test.xml).
其中一种方法使用spring config实例化的对象,它是一个spring组件.类中的一个成员从application.properties派生它的值,application.properties是我们的主要属性文件.通过jUnit访问此值时,它始终为null.我甚至尝试更改属性文件以指向实际的属性文件,但这似乎不起作用.
这是我访问属性文件对象的方式
@Component
@PropertySource("classpath:application.properties")
public abstract class A {
@Value("${test.value}")
public String value;
public A(){
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
public A(String text) {
this();
// do something with text and value.. here is where I run into NPE
}
}
public class B extends A {
//addtnl code
private B() {
}
private B(String text) {
super(text)
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:META-INF/spring/application-core-test.xml",
"classpath:META-INF/spring/application-schedule-test.xml"})
@PropertySource("classpath:application-test.properties")
public class TestD {
@Value("${value.works}")
public String valueWorks;
@Test
public void testBlah() {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
B b= new B("blah");
//...addtnl code
}
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*kal 33
首先,@PropertySource中的application.properties应该读取application-test.properties
文件的名称是什么(匹配这些事情):
@PropertySource("classpath:application-test.properties ")
Run Code Online (Sandbox Code Playgroud)
该文件应位于/src/test/resources
类路径下(在根目录下).
我不明白为什么你要指定一个硬编码到一个名为的文件的依赖项application-test.properties
.该组件仅用于测试环境吗?
通常要做的是在不同的类路径上使用相同名称的属性文件.您可以根据您是否正在运行测试来加载其中一个.
在通常布局的应用程序中,您将拥有:
src/test/resources/application.properties
Run Code Online (Sandbox Code Playgroud)
和
src/main/resources/application.properties
Run Code Online (Sandbox Code Playgroud)
然后像这样注入:
@PropertySource("classpath:application.properties")
Run Code Online (Sandbox Code Playgroud)
更好的做法是将该属性文件作为bean暴露在spring上下文中,然后将该bean注入任何需要它的组件中.这样,您的代码就不会出现对application.properties的引用,您可以使用任何您想要的属性作为源代码.这是一个例子:如何在spring项目中读取属性文件?
sen*_*982 21
至于测试,你应该使用Spring 4.1来覆盖其他地方定义的属性:
@TestPropertySource("classpath:application-test.properties")
Run Code Online (Sandbox Code Playgroud)
测试属性源的优先级高于从操作系统的环境或Java系统属性加载的属性源以及应用程序添加的属性源,如@PropertySource
归档时间: |
|
查看次数: |
95661 次 |
最近记录: |