对于测试私有方法的意义有不同的看法,例如,here https://softwareengineering.stackexchange.com/questions/16732/unit-testing-internal-components and here https://stackoverflow.com/questions/2225431/integration-testing-private-classes-and-methods。我个人认为是有道理的,问题是如何正确地去做。
在 C++ 中你可以使用#define hack https://stackoverflow.com/questions/3676664/unit-testing-of-private-methods或进行测试类friend
,在 C# 中有内部可见属性 https://stackoverflow.com/questions/2225431/integration-testing-private-classes-and-methods,但在 Java 中我们要么必须使用反射 https://stackoverflow.com/questions/2811141/is-it-bad-practice-to-use-reflection-in-unit-testing或者让它们“对测试可见”并且像这样注释它们 http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/annotations/VisibleForTesting.html以便明确意图。两者的缺点应该是很明显的。
我认为应该有更好的东西。从...开始
public class Something {
private int internalSecret() {
return 43;
}
}
如果能够在测试代码中调用私有方法就好了,比如
@MakeVisibleForTesting Something something = new Something();
Assert.assertEquals(43, something.internalSecret());
这里注释会默默地将所有调用转换为私有方法something
使用反射。我怀疑是否Lombok http://projectlombok.org可以做到(并且会询问作者)。
事实证明,做这么多魔法很可能太复杂了,而且无论如何都需要一些时间,所以我正在寻找一些替代方案。也许用类似的东西来注释被测试的类@Decapsulate
并使用注释处理器生成一个类Decapsulated_Something
看起来像
public class Decapsulated_Something {
public Decapsulated_Something(Something delegate) {
this.delegate = delegate
}
public boolean internalSecret() {
// call "delegate.internalSecret()" using reflection
}
...
}
这将允许使用
Decapsulated_Something something = new Decapsulated_Something(new Something());
Assert.assertEquals(43, something.internalSecret());
我对注释处理没有太多经验,所以我先在这里问:
- 实施起来有多复杂?
- 我忘记了什么?
- 您总体上对此有何看法?
看来这个实现起来很麻烦。这可能不值得。而只是将方法包设为默认值。
但是,如果您确定要调用私有方法,则可以使用设置可访问 http://download.oracle.com/javase/6/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible%28java.lang.reflect.AccessibleObject%5B%5D,%20boolean%29 in yourDecapsulated_something
类允许通过反射调用。所以这相当简单。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)