初始化一个常数JUnit的从属性文件获取其自身从pom.xml文件初始化

问题描述:

*请原谅错综复杂的标题*初始化一个常数JUnit的从属性文件获取其自身从pom.xml文件初始化

背景

/pom.xml

... 
<foo.bar>*</foo.bar> 
... 

/src/main/resources/config.properties

... 
foo.bar=${foo.bar} 
... 

Config.java

... 

public final static String FOO_BAR; 

static { 
    try { 
     InputStream stream = Config.class.getResourceAsStream("/config.properties"); 
     Properties properties = new Properties(); 
     properties.load(stream); 
     FOO_BAR = properties.getProperty("foo.bar"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

... 

问题

在/ src目录/主/ java中,我使用的MyClass.java Config.FOO_BAR。如果我想测试在MyClass/src目录使用JUnit与MyClassTest.java /测试/ java文件夹,我怎么能加载属性,以便Config.FOO_BAR不断得到初始化?

我试着用foo.bar=*在/ src/test/resources中添加一个很难写的config.properties,但它仍然无法初始化。

+1

你*有*使用静态初始化这样呢?从根本上说,你已经编写了难以测试的代码......我希望你避免使用静态的过多。 –

+0

@JonSkeet你的意思是我应该每次我需要他们,而不是他们的值作为常数更好的负载特性? – sp00m

我可以使它在你的pom.xml和你Config.java改变一些工作。如果运行Config

public class Config { 
    public final static String FOO_BAR; 

    static { 
     InputStream stream = Config.class.getResourceAsStream("/config.properties"); 
     Properties properties = new Properties(); 
     try { 
      properties.load(stream); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      // You will have to take some action here... 
     } 
     // What if properties was not loaded correctly... You will get null back 
     FOO_BAR = properties.getProperty("foo.bar"); 
    } 

    public static void main(String[] args) { 
     System.out.format("FOO_BAR = %s", FOO_BAR); 
    } 
} 

输出:

这些行添加到您的pom.xml

<project> 
    ... 
    <build> 
     <resources> 
      <resource> 
       <directory>src/main/resources</directory> 
       <filtering>true</filtering> 
      </resource> 
     </resources> 
    </build> 
</project> 

,并更改Config.java一些行的顺序

FOO_BAR = * 

免责声明

我不知道你有什么样的目的与设置这些静态配置值。我只是让它工作。

package com.*; 

import org.junit.Test; 

import static org.junit.Assert.assertEquals; 

/** 
* @author maba, 2012-09-25 
*/ 
public class SimpleTest { 

    @Test 
    public void testConfigValue() { 
     assertEquals("*", Config.FOO_BAR); 
    } 
} 

没有问题,这个测试:


评论

添加了一个简单的JUnit测试src/test/java/后编辑。

+0

谢谢,但已经有效。现在的问题是运行具有JUnit测试时初始化常数,即*的/ SRC /测试/ java文件夹内Test.java类。 – sp00m

+0

@ sp00m添加了一个简单的测试用例,它工作正常。你必须有其他一些你没有提到的问题。我的设置运行良好。 – maba

+0

@ sp00m顺便说一句,那是什么工作已经?资源过滤或设置“FOO_BAR”? – maba