java mockito 是否应该调用模拟类的默认构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7173358/
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
Is mockito supposed to call default constructor of mocked class?
提问by David Nordvall
I'm trying to create a Mockito mock object of a class with some rather heavy network and transaction behavior which I don't want to have to deal with in the current unit test I'm writing. It does however seem like Mockito calls the default constructor of the actual class when instantiating the mock object. The default constructor does all kinds of things that causes problems in the context of this unit test.
我正在尝试创建一个类的 Mockito 模拟对象,该对象具有一些相当繁重的网络和事务行为,我不想在我正在编写的当前单元测试中处理这些行为。然而,在实例化模拟对象时,Mockito 似乎调用了实际类的默认构造函数。默认构造函数执行在此单元测试的上下文中导致问题的各种事情。
Is Mockito supposed to invoke the default constructor? And is there any way to avoid this behavior?
Mockito 是否应该调用默认构造函数?有什么办法可以避免这种行为吗?
Here's how I create the mock object:
这是我创建模拟对象的方法:
ConcreteClassWithComplexDefaultConstructor mockObject = mock(ConcreteClassWithComplexDefaultConstructor.class);
EDIT: So I figured out what's happening. The default constructor of the concrete class ISN'T invoked (as Luciano pointed out). However, the class' static constructor is invoked. As far as I know, static stuff and Mockito doesn't workd very well but is there any way to handle this, i.e somehow make it ignore the static constructor. I don't have very high hopes, however...
编辑:所以我想出了发生了什么。未调用具体类的默认构造函数(如 Luciano 所指出的)。但是,会调用类的静态构造函数。据我所知,静态的东西和 Mockito 不能很好地工作,但是有没有办法处理这个问题,即以某种方式让它忽略静态构造函数。不过我也没有抱太大的希望。。。
回答by Bringer128
Well, it turns out I was wrong. Mockito uses CGLib and Objenesisto create the Object. If you follow that link it explains how it does notcall the super class constructor.
好吧,事实证明我错了。Mockito 使用CGLib 和 Objenesis创建对象。如果您点击该链接,它会解释它如何不调用超类构造函数。
This is easily tested with the following code:
这可以使用以下代码轻松测试:
public class Test
public Test() {
// Never called.
System.out.println("Constructor was called.");
}
public static void main(String[] args) {
Test test = mock(Test.class);
}
回答by Luciano Fiandesio
No, Mockito doesn't call the default constructor of the mocked class.
不,Mockito 不会调用模拟类的默认构造函数。