PowerMock可以为测试用例实例化内部类吗? [英] Can PowerMock instantiate an inner class for test cases?
问题描述
我正在尝试测试一个包含多个私有类的类(是的,我知道这通常被认为是可测试性的不良实践,但这个问题与设计原则无关)。我的课程看起来像这样:
I'm attempting to test a class with a number of private classes (yes, I know this is generally considered poor practice for testability, but this question is not in regards to design principles). My class would look something like this:
public class EnclosingClass {
.
.
.
private class InnerClass implements InnerClassType {
public InnerClass(){ /* do stuff */}
public int InnerClassMethod();
}
}
-
InnerClassType
是一个公共接口 InnerClassType
is a public interface
我已经尝试通过执行以下方法用powermock实例化类: / p>
I've tried instantiating the classes with powermock by doing:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
Constructor constructor = Whitebox.getConstructor(clazz, null);
InnerClassType innerClass = (InnerClassType) constructor.newInstance(null);
以及:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
InnerClassType innerClass = (InnerClassType) Whitebox.invokeConstructor(clazz);
然而,在两次尝试中我得到 ConstructorNotFoundException
However, on both attempts I get a ConstructorNotFoundException
是否可以实例化这些内部类?如果是这样,我哪里出错了?
Is it possible to instantiate these inner classes? If so, where am I going wrong?
推荐答案
您应该可以通过以下mod将您的ConstructorNotFoundExeception移到第一个努力:
You should be able to move past your ConstructorNotFoundExeception via the following mods to your first effort:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
Constructor constructor = Whitebox.getConstructor(clazz, EnclosingClass.class);
InnerClassType innerClass = (InnerClassType) constructor.newInstance(new EnclosingClass());
由于你的内部类不是静态的,它隐含地期望来自外部类的this引用。使用这种方法,看起来你必须明确它。
Since your inner class is not static, it implicitly expects a "this" reference from the outer class. Using this method, looks like you have to get explicit with it.
这篇关于PowerMock可以为测试用例实例化内部类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!