我需要访问一个私有地图进行单元测试,但无法实现。
主类:
public class TestMe{
private Map<String, SomeObject> testMap = new HashMap<String, SomeObject>();
}
单元测试:
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);
}
}
异常:
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)