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 } } 

首先,@PropertySource中的application-test.properties应该读取application-test.properties如果这是文件的名称(匹配这些事情):

 @PropertySource("classpath:application-test.properties ") 

该文件应位于/src/test/resources类路径下(在根目录下)。

我不明白你为什么要指定一个硬编码到一个名为application-test.properties的文件的依赖项。 该组件仅用于测试环境吗?

通常要做的是在不同的类路径上使用相同名称的属性文件。 您可以根据您是否正在运行测试来加载其中一个。

在通常布局的应用程序中,您将拥有:

 src/test/resources/application.properties 

 src/main/resources/application.properties 

然后像这样注入:

 @PropertySource("classpath:application.properties") 

更好的做法是在Spring上下文中将该属性文件公开为bean,然后将该bean注入任何需要它的组件中。 这样,您的代码就不会出现对application.properties的引用,您可以使用任何您想要的属性作为源代码。 这是一个例子: 如何在spring项目中读取属性文件?

至于测试,你应该使用Spring 4.1,它将覆盖其他地方定义的属性:

 @TestPropertySource("classpath:application-test.properties") 

测试属性源的优先级高于从操作系统环境或Java系统属性加载的属性源以及应用程序添加的属性源,如@PropertySource