When writing test code with jUnit etc.
System.You may want to temporarily replace the value of the system environment variable that you get with getenv.
I will describe two implementations, one that does not use the library and the other that uses PowerMock.
Dependency
Java 8
* I think it will work with Java 7.
# Implementation without library
The system environment variable ``` TMEP``` has been replaced.
```java
import org.junit.Test;
import java.lang.reflect.Modifier;
import java.lang.reflect.Field;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class EnvironmentTest {
@Test
public void replaceEnvironment() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
//Get Final Class methods and make them accessible
Class<?> clazz = Class.forName("java.lang.ProcessEnvironment");
Field theCaseInsensitiveEnvironment = clazz.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironment.setAccessible(true);
//Replace only the system environment variables you need
Map<String,String> sytemEnviroment = (Map<String, String>) theCaseInsensitiveEnvironment.get(null);
sytemEnviroment.put("TEMP","/MY_TEMP_DIR");
assertEquals(System.getenv("TEMP"),"/MY_TEMP_DIR");
}
}
PowerMock
PowerMock is relatively easy to implement. However, Class needs to be annotated.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ System.class })
public class EnvironmentWithPowerMockTest {
@Test
public void replaceEnvironment(){
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv("TEMP")).thenReturn("/MY_TEMP_DIR");
assertEquals(System.getenv("TEMP"),"/MY_TEMP_DIR");
}
}
The sample source code is below. https://github.com/amanoese/java-reflection-sample
The source code of System Rules was similar, so basically this is okay. https://github.com/stefanbirkner/system-rules/blob/master/src/main/java/org/junit/contrib/java/lang/system/EnvironmentVariables.java#L165-L190
https://qiita.com/5at00001040/items/83bd7ea85d0f545ae7c3 https://blogs.yahoo.co.jp/dk521123/37484564.html https://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java
Recommended Posts