java使用jUnit测试私有方法(private method),,使用junit测试私有方
分享于 点击 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)
方法
用户点评