mockito 如何用JUnit5模拟系统getenv()

toe95027  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(279)

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

<dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>2.23.0</version>
        <scope>test</scope>
    </dependency>

下面是我的测试示例:

@ExtendWith(MockitoExtension.class) 
public class TestEnvVariable {

  @Mock
  System system;

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

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

z8dt9xmd

z8dt9xmd1#

我认为你可以在junit4使用EnviromentVariableRule
看看这个链接:https://www.baeldung.com/java-system-stubs#2-junit-4-environment-variables

qzwqbdag

qzwqbdag2#

模拟System似乎是不可能的。请参见here
系统存根也可能是JUnit5的一个很好的替代方案

相关问题