如何测试私有函数或具有私有方法,字段或内部类的类? [英] How do I test a private function or a class that has private methods, fields or inner classes?

查看:116
本文介绍了如何测试私有函数或具有私有方法,字段或内部类的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何对具有内部私有方法,字段或嵌套类的类进行单元测试(使用xUnit)?或通过具有内部链接(在C/C ++中)还是在私有( anonymous )命名空间中?

How do I unit test (using xUnit) a class that has internal private methods, fields or nested classes? Or a function that is made private by having internal linkage (static in C/C++) or is in a private (anonymous) namespace?

仅为了能够运行测试而更改方法或函数的访问修饰符似乎很糟糕.

It seems bad to change the access modifier for a method or function just to be able to run a test.

推荐答案

更新:

大约10年后,测试私有方法或任何无法访问的成员的最佳方法可能是通过@Jailbreak ="noreferrer">流形框架.

Some 10 years later perhaps the best way to test a private method, or any inaccessible member, is via @Jailbreak from the Manifold framework.

@Jailbreak Foo foo = new Foo();
// Direct, *type-safe* access to *all* foo's members
foo.privateMethod(x, y, z);
foo.privateField = value;

这样,您的代码将保持类型安全和可读性.没有设计上的妥协,也没有为了测试而过度曝光的方法和字段.

This way your code remains type-safe and readable. No design compromises, no overexposing methods and fields for the sake of tests.

如果您使用的是旧版 Java 应用程序,并且不允许更改方法的可见性,则测试私有方法的最佳方法是使用

If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.

内部,我们使用助手来获取/设置privateprivate static变量以及调用privateprivate static方法.以下模式将使您几乎可以执行与私有方法和字段相关的所有操作.当然,您不能通过反射更改private static final变量.

Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final variables through reflection.

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);


注释:
1. TargetClass.getDeclaredMethod(methodName, argClasses)可让您查看private方法.同样的事情也适用 getDeclaredField.
2. setAccessible(true)必须与私人玩耍.

Notes:
1. TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for getDeclaredField.
2. The setAccessible(true) is required to play around with privates.

这篇关于如何测试私有函数或具有私有方法,字段或内部类的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆