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)
letsprivate
methods. same thing appliesgetdeclaredfield
.
2.setaccessible(true)
required play around privates.
Comments
Post a Comment