How to Mock System.getenv() with JUnit5

Viewed 2300

I want to mock the System.getenv() method. I found only solutions for JUnit4 and PowerMockito. I use the following dependency:

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

Here is my example of the test:

@ExtendWith(MockitoExtension.class) 
public class TestEnvVariable {

  @Mock
  System system;

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

How to Mock System.getenv() with JUnit5?

2 Answers

It does not seem to be possible to mock System. See here

System Stubs might also be a good alternative for JUnit5

Related