初始化一个常数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,但它仍然无法初始化。
答
我可以使它在你的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/
后编辑。
你*有*使用静态初始化这样呢?从根本上说,你已经编写了难以测试的代码......我希望你避免使用静态的过多。 –
@JonSkeet你的意思是我应该每次我需要他们,而不是他们的值作为常数更好的负载特性? – sp00m