junit没有加载属性文件

时间:2012-01-25 21:23:54

标签: spring properties junit

我正在尝试运行一些需要来自我在生产中使用的.properties文件中的值的测试。我可以验证测试是通过-DapplicationProperties="fname"获取属性文件的位置,但是它没有被解析。我也在使用弹簧,它是否通常会为我解析这个?如果没有,junit应该自动执行此操作吗?如果没有,通过System.getProperty()确保我的所有测试都可以使用这些属性的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

Spring和JUnit都不会仅仅因为有参数而解析属性文件。

要在Spring中加载属性文件,最简单的方法是使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

请参阅Spring Reference: 3.8.2.1 Example: the PropertyPlaceholderConfigurer示例。

请参阅此博客,了解如何在不同类型的属性之间进行distingush以及存储方式:http://www.summa-tech.com/blog/2009/04/20/6-tips-for-managing-property-files-with-spring/

答案 1 :(得分:0)

我创建了一个名为System Rules的库,用于测试使用java.lang.System的代码。使用这个库,您可以编写如下的JUnit测试:

import static org.junit.Assert.assertEquals;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.Rule;
import org.junit.Test;

public void MyTest {
  @Rule
  public ProvideSystemProperty myPropertyHasMyValue
    = new ProvideSystemProperty("MyProperty", "MyValue");

  @Test
  public void propertyIsThere() {
    assertEquals("MyValue", System.getProperty("MyProperty"));
  }
}

也可以使用属性文件中的属性:

@Rule
public ProvideSystemProperty properties
 = ProvideSystemProperty.fromFile("/home/myself/example.properties");

@Rule
public ProvideSystemProperty properties
 = ProvideSystemProperty.fromResource("example.properties");