5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javaでリフレクションによるシステム環境変数の差し替え

Last updated at Posted at 2019-01-21

jUnitなどでテストコードを記述する際に、
System.getenvで取得するシステム環境変数の値を一時的に差し替えたい時があると思います。

ライブラリを使わない実装とPowerMockによる実装の2つを記載します。

Dependency

Java 8
*Java 7でも動くと思います。

ライブラリを使わない実装

システム環境変数のTMEPを差し替えています。

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 {
	//Final Classのメソッドを取得しアクセス可能に
	Class<?> clazz = Class.forName("java.lang.ProcessEnvironment");
    Field theCaseInsensitiveEnvironment = clazz.getDeclaredField("theCaseInsensitiveEnvironment");
	theCaseInsensitiveEnvironment.setAccessible(true);

	//システム環境変数で必要なものだけを差し替える
	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だと比較的容易に実装できます。
ただし、Classにアノテーションが必要になります。

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

備考

サンプルのソースコードは下記です。
https://github.com/amanoese/java-reflection-sample

System Rulesのソースコードでも似たような処理だったので基本的にはこれで問題ないかと
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

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?