8

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?

GreenJenks
  • 111
  • 1
  • 9

4 Answers4

1

You can create the object in the production code and mock that object in test.

In production code

Object Env{
       fun getVar() = System.getEnv("key")
}

then call with Env in production code

val callObject = Env.getVar()

In test file

@BeforeEach
fun setup() {
mockkObject(Env)
}

In test you can enter this -

every { Env.getVar() } returns "value"
0

I think you can use EnviromentVariableRule at junit4.

Look at this link: https://www.baeldung.com/java-system-stubs#2-junit-4-environment-variables

dodoconr
  • 113
  • 2
  • 9
0

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

System Stubs might also be a good alternative for JUnit5

0

Add the below configuration in maven-surefire-plugin dependency of your pom.xml, and run your junit test case as it is without making explicit changes related to System.getEnv() like Mocking System.class. This is not allowed/required.

If for example below is how your environment variable looks like :-

  • Env Variable name := PROPERTY_NAME
  • Env Variable Value := PROPERTY_VALUE

And if you access that environment variable using the below line Java :- System.getEnv("PROPERTY_NAME");

Make the below changes to your pom.xml :-

<dependency>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.22.2</version>
  <configuration>
   <environmentVariables>
      <PROPERTY_NAME>PROPERTY_VALUE</PROPERTY_NAME>
   </environmentVariables>
  </configuration>
</dependency>