欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java使用jUnit测试私有方法(private method),,使用junit测试私有方

来源: javaer 分享于  点击 8710 次 点评:265

java使用jUnit测试私有方法(private method),,使用junit测试私有方


使用junit测试私有方法,需要使用java的反射技术

如下代码是典型的通过反射调用方法的示例代码:

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

如果需要,也可以通过反射的方式设置私有字段的值:

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

说明:

targetClass.getDeclaredMethod(methodName, argClasses) 返回私有方法. getDeclaredField用来返回私有字段.在调用私有方法之前,必须调用setAccessible(true)方法
相关栏目:

用户点评