Reputation: 1371
Using a combination of testng and jmockit to do some unit testing. In a method I am testing, it tries to access a system property that I set using a JBoss deploy script, therefore my unit test doesn't have access to the entire JBoss environment to access the properties, so it returns null when testing that method. Tried mocking and setting the system variable directly in my test, but the system property is still returning null in the class that I am testing.
The class being tested:
//returns the correct value in the application but returns null for the test
public static final String webdavrootDir = System.getProperty("property.name");
public String getFileUrl(){
StringBuilder sb = new StringBuilder();
return sb.append(webdavrootDir)
.append(intervalDir)
.append(fileName)
.toString();
}
The test:
@Test
public void getUrl(@Mocked System system){
system.setProperty("property.name", "https://justatest.com/dav/bulk");
String fileUrl = csvConfig.getFileUrl();
assertEquals(fileUrl, "https://justatest.com/dav/bulk/otherstuff");
}
The test finds the value null/otherstuff
but expects https://justatest.com/dav/bulk/otherstuff
I have also tried setting the system property in a testng @BeforeMethod
method without any success.
Upvotes: 0
Views: 14178
Reputation: 1994
If you want to use jMockit, then you need to make sure it is done before your class-under-test is loaded (because of the static field).
@BeforeClass
public static void fakeSystemProperty() {
new MockUp<System>() {
@Mock
public String getProperty(String key) {
return "https://justatest.com/dav/bulk";
}
};
}
Another way would be to modify the class-under-test and partially mock this one, e.g.:
public class CsvConfig {
private static final String webdavrootDir = System.getProperty("property.name");
public static String getProperty() {
return webdavrootDir;
}
}
The test:
@BeforeClass
public static void fakeSystemProperty() {
new MockUp<CsvConfig>() {
@Mock
public String getProperty() {
return "https://justatest.com/dav/bulk";
}
};
}
Upvotes: 1
Reputation: 545
Make sure you call System.setProperty("property.name", "https://justatest.com/dav/bulk");
before the class being tested is instantiated, otherwise the static field will always be null.
Consider using a @BeforeClass
setup method for this:
@BeforeClass
public static void setup() {
System.setProperty("property.name", "https://justatest.com/dav/bulk");
// Instantiate your CsvConfig instance here if applicable.
}
and then
@Test
public void getUrl(){
System.setProperty("property.name", "https://justatest.com/dav/bulk");
String fileUrl = csvConfig.getFileUrl();
assertEquals(fileUrl, "https://justatest.com/dav/bulk/otherstuff");
}
Upvotes: 4