Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock System class to get system properties

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.

like image 396
sailaja.vellanki Avatar asked Dec 05 '13 15:12

sailaja.vellanki


2 Answers

System class is declared as final and cannot be mocked by libraries such as PowerMock. Several answers posted here are incorrect. If you are using Apache System Utils you can use getEnvironmentVariable method instead of calling System.getenv directly. SystemUtils can be mocked since it is not declared as final.

like image 114
ekcrisp Avatar answered Sep 18 '22 14:09

ekcrisp


There are certain classes PowerMock can't mock in the usual way. See here:

  • https://code.google.com/p/powermock/wiki/MockSystem

This, however, may still not work. In order of "good design" preference, you can fall back to these:

  1. Refactor your code! Using a System property for passing a file path around is probably not the best way. Why not use a properties file loaded into a Properties object? Why not use getters/setters for the components that need to know this path? There are many better ways to do this.

    The only reason I could think of not to do this is you're trying to wrap a test harness around code you "can't" modify.

  2. Use @Before and @After methods to set the System property to some known value for the test(s). You could even make it part of the @Test method itself. This will be FAR easier than attempting to mock through PowerMock. Just call System.setProperty("my_files_path","fake_path");

like image 42
Matt Lachman Avatar answered Sep 20 '22 14:09

Matt Lachman