If you have somewhat of a legacy application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.
Internally we're using helpers to get/set
private static variables as well as invoke
private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course you can't change
private static finalvariables through reflection.
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
return method.invoke(targetObject, argObjects);
And for fields:
Field field = targetClass.getDeclaredField(fieldName);
targetClass.getDeclaredMethod(methodName, argClasses) lets you look into
privatemethods. The same thing applies for
setAccessible(true) is required to play around with privates.
- answered 5 years ago
- Sunny Solu