Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock System.getenv() with JUnit5

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?

like image 280
GreenJenks Avatar asked Nov 23 '25 08:11

GreenJenks


2 Answers

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"
like image 137
Minaam Qureshi Avatar answered Nov 25 '25 22:11

Minaam Qureshi


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

System Stubs might also be a good alternative for JUnit5

like image 45
Holger Veltrup Avatar answered Nov 25 '25 22:11

Holger Veltrup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!