如何使用 JUnit5 模拟 System.getenv()

Gre*_*nks 12 java mockito junit5 junit-jupiter

我想模拟 System.getenv() 方法。我只找到了 JUnit4 和 PowerMockito 的解决方案。我使用以下依赖项:

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>2.23.0</version>
        <scope>test</scope>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

这是我的测试示例:

@ExtendWith(MockitoExtension.class) 
public class TestEnvVariable {

  @Mock
  System system;

  @Test
  public void shouldExpandPropertyContentToMatchingSysEnv() throws Exception {
      when(system.getenv("KEY")).thenReturn("VALUE");
      assertEquals("VALUE", "KEY");
  }
}
Run Code Online (Sandbox Code Playgroud)

如何使用 JUnit5 模拟 System.getenv()?

小智 0

我认为你可以在junit4上使用EnviromentVariableRule

看这个链接: https: //www.baeldung.com/java-system-stubs#2-junit-4-environment-variables