Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access private map through reflection in unit test

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)
like image 858
JSS Avatar asked Jan 20 '26 06:01

JSS


1 Answers

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);
    }
}
like image 171
René Link Avatar answered Jan 23 '26 00:01

René Link



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!