如何使用 JUnit 测试具有内部私有(private)方法、字段或嵌套类的类?
为了能够运行测试而更改方法的访问修饰符似乎很糟糕。
最佳答案
如果您有一些遗留的 Java 应用程序,并且不允许更改方法的可见性,那么测试私有(private)方法的最佳方法是使用 reflection .
在内部,我们使用助手来获取/设置 private
和 private static
变量以及调用 private
和 private static
方法。以下模式将使您可以执行与私有(private)方法和字段相关的几乎所有操作。当然,你不能通过反射改变private static final
变量。
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);
Notes:
TargetClass.getDeclaredMethod(methodName, argClasses)
lets you look intoprivate
methods. The same thing applies forgetDeclaredField
.- The
setAccessible(true)
is required to play around with privates.
关于java - 如何测试具有私有(private)方法、字段或内部类的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6543135/