I recently started working on TDD for a project exit and ran into several issues, one of which is mentioned below
I have a private variable that needs to be mocked at the test class, and the variable looks below
private Class<XYZ> cls = XYZ.class;
later this cls variable is used as a measure for one of the methods as className
private List create(Class className, Object objectTO, List<String> names)
I know that private variables can be mocked and I mocked a private variable in my test case by following these steps.
- Announced
java.lang.reflect.Field; Field field = PowerMockito.field(XYZ.class,"cls");field.set(XYZ.class, "objectOfXYZClass");
When I run my test class, I get below the error
java.lang.IllegalArgumentException: Can not set java.lang.Class field com.tools.XYZ.cls to java.lang.Class
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.set(UnsafeObjectFieldAccessorImpl.java:75)
at java.lang.reflect.Field.set(Field.java:680)
Please someone can help me with this and let me know what I am missing.
PS: @preparefortest , @runwith(powermockrunner.class)