Access private map through reflection in unit test
java, reflection, unit-testing
Solution
You must invoke `Field.get()` with the `TestMe` object.
TestMe obj = new TestMe();
....
Map<String, SomeObject> refMap = (HashMap<String, SomeObject>) = field.get(obj);
Your code invokes `Field.get()` on a new instance of `HashMap`.
field.get(new HashMap<String, Object>()); // This will not work in your case
EDIT to comment: This is not working.
I tried to figure out what could not be working. This is my test code and it works.
public class TestMeTester {
public static class TestMe {
private Map<String, String> testMap = new HashMap<String, String>();
}
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, SecurityException, NoSuchFieldException {
TestMe obj = new TestMe();
Class clazz = obj.getClass();
Field field = clazz.getDeclaredField("testMap");
field.setAccessible(true);
Map<String, String> refMap = (HashMap<String, String>) field.get(obj);
System.out.println("==>" + refMap);
}
}
Problem
I need to access a private map for unit testing but unable to do that. Main class: ``` public class TestMe{ private Map<String, SomeObject> testMap = new HashMap<String, SomeObject>(); } ``` Unit Test: ``` public class TestMeTester{ public testTestMe(){ TestMe obj = new TestMe(); Class clazz = obj.getClass(); Field field = clazz.getDeclaredField("testMap"); field.setAccessible(true); Map<String, SomeObject> refMap = (HashMap<String, SomeObject>) field.get(new HashMap<String, Object>()); System.out.println("==>" + refMap); } } ``` Exception: ``` java.lang.IllegalArgumentException: Can not set java.util.Map field com.xx.TestMe.testMap to java.util.HashMap at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168) at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55) at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ```