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.
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.
There are certain classes PowerMock can't mock in the usual way. See here:
This, however, may still not work. In order of "good design" preference, you can fall back to these:
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With