• support@answerspoint.com

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

411

How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test.

2Answer


0

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 finalvariables through reflection.

Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);

And for fields:

Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);

Notes:
1. targetClass.getDeclaredMethod(methodName, argClasses) lets you look into privatemethods. The same thing applies for getDeclaredField.
2. The setAccessible(true) is required to play around with privates.

  • answered 2 years ago
  • Sunny Solu

0

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 2 years ago
  • Sunny Solu

Your Answer

    Facebook Share