How do I test a private function or a class that has private methods, fields or inner classes?

Technology CommunityCategory: JavaHow do I test a private function or a class that has private methods, fields or inner classes?
VietMX Staff asked 3 years ago
Problem

How do I unit test (using xUnit) a class that has internal private methods, fields or nested classes?

The best way to test private methods is to use reflection.

The following patterns will let you do pretty much anything related to the private methods and fields:

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);