Java 从.properties文件初始化JUnit的常量,该文件从pom.xml文件初始化自身

Java 从.properties文件初始化JUnit的常量,该文件从pom.xml文件初始化自身,java,properties,junit,initialization,constants,Java,Properties,Junit,Initialization,Constants,*请原谅这个复杂的标题* 背景 /pom.xml ... <foo.bar>stackoverflow</foo.bar> ... Config.java ... public final static String FOO_BAR; static { try { InputStream stream = Config.class.getResourceAsStream("/config.properties"); Prope

*请原谅这个复杂的标题*

背景

/pom.xml

...
<foo.bar>stackoverflow</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/main/java中,我正在MyClass.java中使用
Config.FOO\u BAR
。如果我想使用JUnit和MyClassTest.java在/src/test/java文件夹中测试
MyClass
,我如何加载属性,以便初始化
Config.FOO\u栏
常量


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

我可以通过更改
pom.xml
config.java
中的一些内容来实现

将这些行添加到您的
pom.xml


...
src/main/resources
真的
并更改
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
免责声明

我不确定设置这些静态配置值的目的是什么。我刚刚成功了


评论后编辑

src/test/java/
中添加了一个简单的JUnit测试:

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);
    }
}

此测试没有问题。

您必须使用这样的静态初始值设定项吗?基本上,您已经编写了难以测试的代码。。。我强烈建议您避免过度使用静态。@JonSkeet您的意思是我应该在每次需要时加载属性,而不是用它们的值设置常量?谢谢,但这已经奏效了。现在的问题是在使用JUnit运行测试时初始化常量,即/src/Test/java文件夹中的*Test.java类。@sp00m添加了一个简单的测试用例,效果很好。你肯定还有一些你没有提到的问题。我的设置很好。@sp00m顺便问一下,什么已经起作用了?资源筛选或设置
FOO\u栏
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);
    }
}