从 .properties 文件初始化 JUnit 常量,该常量从 pom.xml 文件初始化

2024-03-23

*请原谅复杂的标题*

背景

/pom.xml

...
<foo.bar>stackoverflow</foo.bar>
...

/src/main/resources/config.properties

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

配置文件

...

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

...

Question

在 /src/main/java 中,我正在使用Config.FOO_BAR在 MyClass.java 中。如果我想测试MyClass在 /src/test/java 文件夹中使用 JUnit 和 MyClassTest.java,如何加载属性以便Config.FOO_BAR常量被初始化?

我尝试在 /src/test/resources 中添加一个很难写的 config.propertiesfoo.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);
    }
}

这次测试没有问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 .properties 文件初始化 JUnit 常量,该常量从 pom.xml 文件初始化 的相关文章

随机推荐