Update:
大约10年后,也许测试私有方法或任何无法访问的成员的最佳方法是通过Manifold框架中的101.
@Jailbreak Foo foo = new Foo(); // Direct, *type-safe* access to *all* foo's members foo.privateMethod(x, y, z); foo.privateField = value;
这样,您的代码就保持了类型安全和可读性.没有设计妥协,没有为了测试而过度expose 方法和字段.
如果您有一些遗留的Java应用程序,并且不允许更改方法的可见性,则测试私有方法的最佳方式是使用reflection.
在内部,我们使用帮助器来获取/设置private
和private static
变量,以及调用private
和private static
方法.下面的模式几乎可以让您执行与私有方法和字段相关的任何操作.当然,您不能通过反射更改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: