BBH
-Biz Branding Hub-
投稿日 : 
2020/04/03
更新日 : 
2020/04/03

【Java】ユニットテストでprivateフィールドにアクセスするサンプル

ユニットテストなどでどうしてもPrivateフィールドに対して外からアクセスしたい時があるかと思います。
以下のようにリフレクションを使用することで外からprivateフィールドにアクセスすることができます。

テスト対象

import org.springframework.stereotype.Component;

@Component
public class PrivateReflection {
	private String privateField = "privateField";
}

アクセスするクラス

import java.lang.reflect.Field;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class PrivateReflectionTest {

	@Autowired
	private PrivateReflection privateReclection;

	@Test
	public void test() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        // 対象クラスのプライベートフィールドのオブジェクトをレフレクションで取得
		Field field = this.privateReclection.getClass().getDeclaredField("privateField");

        // フィールドへのアクセスを可能にする
		field.setAccessible(true);

		// フィールドへアクセス
		Assert.assertEquals("privateField", field.get(this.privateReclection));
	}
}

Profile

管理人プロフィール

都内でITエンジニアをやってます。
変遷:中規模SES→独立系SIer→Webサービス内製開発
使用技術はその時々でバラバラですが、C#、AWSが長いです。
どちらかと言うとバックエンドより開発が多かったです。
顧客との折衝や要件定義、マネジメント(10名弱程度)の経験あり。
最近はJava+SpringBootがメイン。

Recommend