Considering question https://stackoverflow.com/a/51980599/7203487. Only one method among methods in class contains System.getenv which needs to be mocked. Problem is I require to take jacoco code coverage which I get as 0% due to use of powemock. Is there a way possible to mock system and attain code coverage with or without powermock?
Asked
Active
Viewed 6,537 times
2 Answers
8
Have a look into the System Rules for JUnit 4, especially the EnvironmentVariables.
public class EnvironmentVariablesTest {
@Rule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
@Test
public void setEnvironmentVariable() {
environmentVariables.set("name", "value");
assertEquals("value", System.getenv("name"));
}
}

Roland Weisleder
- 9,668
- 7
- 37
- 59
-
super. i never knew this before!! thanks for sharing – Gayathri Sep 05 '18 at 06:47
-
@sahlouls please check https://stefanbirkner.github.io/system-rules/download.html – T D Apr 17 '19 at 15:11
-
@t-d the main issue is the lib is instable, my builds fail often – sahlouls Apr 17 '19 at 15:20
-
I have a build with version 1.19.0 and it works. Can you attach the build logs with error? – T D Apr 22 '19 at 13:11
-
1Wait..the above is third party library? meaning your own custom library or inbuild in Junit? – Stunner Aug 16 '21 at 17:33
2
Adding to @Roland Weisleder.
EnvironmnetVariables is not part of junit . you need to add below dependency
https://stefanbirkner.github.io/system-rules/download.html
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
<version>1.19.0</version>
<scope>test</scope>
</dependency>

T D
- 1,080
- 2
- 13
- 20
-
He already added link for system rules. And answer is already accepted. – Gayathri Apr 24 '19 at 06:35
-
Thanks @T D .. I was thinking the Ronald code is inbuilt in junit.... I was looking for something in built in JUNIT.... Not everyone has luxury to add third party libraries..especially if you are working for someone else – Stunner Aug 16 '21 at 17:33