【发布时间】:2016-01-03 15:13:31
【问题描述】:
我有一个 jUnit 测试,它有自己的属性文件(application-test.properties)和它的 spring 配置文件(application-core-test.xml)。
其中一种方法使用由 spring config 实例化的对象,即 spring 组件。类中的成员之一从我们的主要属性文件 application.properties 派生其值。通过 jUnit 访问此值时,它始终为空。我什至尝试将属性文件更改为指向实际的属性文件,但这似乎不起作用。
这是我访问属性文件对象的方式
@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
}
}
【问题讨论】:
-
如何实例化
A的实例?我的猜测是您正在使用new而不是从 ApplicationContext 查找它 -
那么@PropertySource 中的application.properties 不应该读取application-test.properties 吗?
-
@Lance Java:是的,我正在使用新的。将尝试从 ApplicationContext 查找..
-
@RobertMoskal 我试过了,但似乎也没有用。
-
您需要@ComponentScan 或
<context:component-scan/>来获取您的@Component
标签: java spring junit spring-junit