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


how use junit test class has internal private methods, fields or nested classes?

it seems bad change access modifier method able run test.

if have of legacy application, , you're not allowed change visibility of methods, best way test private methods use reflection.

internally we're using helpers get/set private , private static variables invoke private , private static methods. following patterns let pretty related private methods , fields. of course can't change private static final variables through reflection.

method method = targetclass.getdeclaredmethod(methodname, argclasses); method.setaccessible(true); return method.invoke(targetobject, argobjects); 

and fields:

field field = targetclass.getdeclaredfield(fieldname); field.setaccessible(true); field.set(object, value); 

notes:
1. targetclass.getdeclaredmethod(methodname, argclasses) lets private methods. same thing applies getdeclaredfield.
2. setaccessible(true) required play around privates.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -