*请原谅错综复杂的标题*
背景
/pom.xml
...
<foo.bar>stackoverflow</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中,我使用Config.FOO_BAR
在MyClass.java。 如果我想测试MyClass
在/ src目录/ test / java下使用JUnit与MyClassTest.java文件夹,我怎么可以加载属性,以便Config.FOO_BAR
不断得到初始化?
我试图/ src目录/测试/与资源范围内添加一个很难写的config.properties foo.bar=stackoverflow
,但它仍然无法初始化。
我可以使它通过改变一些在你的工作pom.xml
和你Config.java
。
添加这些行到您pom.xml
:
<project>
...
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
并改变在某些行的顺序Config.java
:
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);
}
}
如果运行输出Config
:
FOO_BAR = stackoverflow
放弃
我不知道你有什么样的目的与设置这些静态配置值。 我只是做它的工作。
评论后编辑
添加了一个简单的JUnit测试到src/test/java/
:
package com.stackoverflow;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author maba, 2012-09-25
*/
public class SimpleTest {
@Test
public void testConfigValue() {
assertEquals("stackoverflow", Config.FOO_BAR);
}
}
没有问题与这个测试。
文章来源: Initialize a constant for JUnit from a .properties file which gets itself initialized from the pom.xml file