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?
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"
It does not seem to be possible to mock System. See here
System Stubs might also be a good alternative for JUnit5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With