Reputation: 48817
*Please forgive the intricate title*
Background
/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();
}
}
...
Question
In /src/main/java, I'm using Config.FOO_BAR
in MyClass.java. If I want to test MyClass
in a /src/test/java folder using JUnit with MyClassTest.java, how can I load the properties so that the Config.FOO_BAR
constant get initialized?
I tried to add a hardly-written config.properties within /src/test/resources with foo.bar=stackoverflow
, but it still can't get initialized.
Upvotes: 2
Views: 3554
Reputation: 48075
I could make it work by changing some in your pom.xml
and your Config.java
.
Add these lines to your pom.xml
:
<project>
...
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
And change the order of some lines in 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);
}
}
Output if running Config
:
FOO_BAR = stackoverflow
Disclaimer
I am not sure what purpose you have with setting these static config values. I just made it work.
Edit after comment
Added a simple JUnit test to 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);
}
}
No problems with this test.
Upvotes: 1