模拟 System.getenv 除了 powermock

Mocking System.getenv other than with powermock

正在考虑问题 。 class 中的方法中只有一个方法包含 System.getenv 需要被模拟。问题是我需要采用 jacoco 代码覆盖率,由于使用 powemock,我得到的覆盖率为 0%。有没有办法模拟系统并在有或没有 powermock 的情况下获得代码覆盖率?

查看 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。

EnvironmnetVariables 不是 junit 的一部分。您需要添加以下依赖项

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>