Mock System class to get system properties

environment-variables, java, mocking, powermock, system

Solution

Thanks Satish. This works except with a small modification. I wrote PrepareForTest(PathFinder.class), preparing the class I am testing for test cases instead of System.class

Also, as mock works only once, I called my method right after mocking. My code just for reference:

@RunWith(PowerMockRunner.class)
@PrepareForTest(PathInformation.class)
public class PathInformationTest {

    private PathFinder pathFinder = new PathFinder();

@Test
    public void testValidHTMLFilePath() { 
        PowerMockito.mockStatic(System.class);
        PowerMockito.when(System.getProperty("my_files_path")).thenReturn("abc");
        assertEquals("abc",pathFinder.getHtmlFolderPath());
    }
}

Problem

I have a folder path set in system variable through JVM arguments in Eclipse and I am trying to access it in my class as: `System.getProperty("my_files_path")`. While writing junit test method for this class, I tried mocking this call as test classes do not consider JVM arguments. I have used PowerMockito to mock static System class and tried returning some path when `System.getProperpty` is being called. Had `@RunWith(PowerMockRunner.class)` and `@PrepareForTest(System.class)` annotations at class level. However, System class is not getting mocked as a result I always get null result. Any help is appreciated.

Original source