Search code examples
javaunit-testingtestngjmockitsystem-properties

Set system property in jmockit unit test


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.


Solution

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