Organizational Research By

Surprising Reserch Topic

How to test a class that has private methods, fields or inner classes

asked May 15, 2015 in Core java by rajesh
0 votes

Related Hot Questions

2 Answers

0 votes
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 and private static variables as well as invoke private and 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 final variables through reflection.

Method method = targetClass.getDeclaredMethod(methodName, argClasses);
return method.invoke(targetObject, argObjects);
And for fields:

Field field = targetClass.getDeclaredField(fieldName);
field.set(object, value);
1. targetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for  getDeclaredField.
2. The setAccessible(true) is required to play around with privates.
answered May 15, 2015 by rajesh
0 votes

The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:

  1. The private method is dead code
  2. There is a design smell near the class that you are testing
  3. The method that you are trying to test should not be private
answered May 15, 2015 by rajesh