java PowerMock 可以为测试用例实例化内部类吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13201943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can PowerMock instantiate an inner class for test cases?
提问by josh-cain
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
is a public interface
InnerClassType
是公共接口
I've tried instantiating the classes with powermock by doing:
我尝试通过执行以下操作使用 powermock 实例化类:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
Constructor constructor = Whitebox.getConstructor(clazz, null);
InnerClassType innerClass = (InnerClassType) constructor.newInstance(null);
and also:
并且:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
InnerClassType innerClass = (InnerClassType) Whitebox.invokeConstructor(clazz);
However, on both attempts I get a ConstructorNotFoundException
但是,在两次尝试中,我都得到了 ConstructorNotFoundException
Is it possible to instantiate these inner classes? If so, where am I going wrong?
是否可以实例化这些内部类?如果是这样,我哪里出错了?
采纳答案by Brian Henry
You should be able to move past your ConstructorNotFoundExeception via the following mods to your first effort:
您应该能够通过以下模块将 ConstructorNotFoundException 移到您的第一项工作:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
Constructor constructor = Whitebox.getConstructor(clazz, EnclosingClass.class);
InnerClassType innerClass = (InnerClassType) constructor.newInstance(new EnclosingClass());
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.
由于您的内部类不是静态的,它隐含地期望来自外部类的“this”引用。使用这种方法,看起来您必须明确使用它。
回答by Samir
You can mock it like this:
你可以像这样模拟它:
InnerClassType innerClass = (InnerClassType) Mockito.mock(
Class.forName(EnclosingClass.class.getName() + "$InnerClass")
);