Spring jUnit 测试属性文件

新手上路,请多包涵

我有一个 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

    }
}

原文由 Nikhil Das Nomula 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 729
1 个回答

首先,@PropertySource 中的 application.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")

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

原文由 Robert Moskal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题