Replacing system environment variables by reflection in java

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");
  }
}

Remarks

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

reference

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

Replacing system environment variables by reflection in java
Handle system environment variables in Spring application.properties
When there are environment variables in Java tests
JavaFX environment construction in Java 13
Java Spring environment in vs Code
How to name variables in Java
Setting project environment variables in intelliJ
Examine the system information of AWS Lambda operating environment in Java
Java container performance degradation in Menicoa environment
Duplicate Map sorted by key in Java
[Docker] Use environment variables in Nginx conf
How to use environment variables in RubyOnRails
Do not declare variables in List in Java
Java application development environment created in VM environment
How to concatenate strings separated by commas using StringJoiner even in java7 environment
[Java] Dynamic method call by reflection of enum (enum)
Solution for NetBeans 8.2 not working in Java 9 environment
What I learned in Java (Part 2) What are variables?
Library "OSHI" to get system information in Java
Points stuck in building VSCode & Java development environment
[Java] output, variables
Partization in Java
[Java] Environment construction
Changes in Java 11
Rock-paper-scissors in Java
Java environment construction
[WIP] Java variables
Pi in Java
FizzBuzz in Java
[LeJOS] Let's program mindstorm-EV3 in Java [Environment construction part 2]
How to call functions in bulk with Java reflection
How to create a Java environment in just 3 seconds
Read the packet capture obtained by tcpdump in Java
Maven fails in Java7 environment (Received fatal alert: protocol_version)
[Java] Difference between static final and final in member variables
[Java] Refer to and set private variables with reflection
[Java] Get the file in the jar regardless of the environment
[JAVA] [Spring] [MyBatis] Use GROUP BY in SQL Builder
Differences in code when using the length system in Java