【问题标题】:junit not loading properties filejunit没有加载属性文件
【发布时间】:2012-02-19 02:20:29
【问题描述】:

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

【问题讨论】:

    标签: spring properties junit


    【解决方案1】:

    我创建了一个名为 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");
    

    【讨论】:

    • 我更喜欢使用在生产中使用的属性文件,以防将来发生变化
    • 系统规则 1.1.0 支持属性文件。
    • 所以(来自两个最新示例),我可以在加载文件后使用System.getProperty("somethingFromTheFile"); 吗?这就是目标。 Oracle 的 UCP 需要该属性,因此必须通过 System.getProperty (afaik) 获得它。
    • 是的,您可以在测试中使用文件中的属性。
    【解决方案2】:

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

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

    参见Spring Reference: 3.8.2.1 Example: the PropertyPlaceholderConfigurer 示例。

    有关区分不同类型属性和存储方式的方法,请参阅此博客:http://www.summa-tech.com/blog/2009/04/20/6-tips-for-managing-property-files-with-spring/

    【讨论】:

    • 嗯,这可能是解析它的原因吗? <context:component-scan base-package="com.stuffs.controller" />
    • @Josh 我不明白你的评论!
    • 抱歉,我的dispatcher-servlet.xml 文件中有上述行。这可能是导致属性文件被spring解析的原因吗?
    • 否 - 它会在 com.stuffs.controller 和子包中搜索带有 @Respository@Service@Controller@Component 注释的类并实例化它。
    • 那么我不确定如何解析属性文件。就像我说的那样,我们将参数 -DapplicationProperties=path/here/something.properties 传递给 jvm,我可以确认这一点。我会继续寻找......
    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多