mockito 是否应该调用模拟类的默认构造函数?
我正在尝试创建一个类的 Mockito 模拟对象,该对象具有一些相当重的网络和事务行为,我不想在我正在编写的当前单元测试中处理这些行为。然而,在实例化模拟对象时,Mockito 似乎确实调用了实际类的默认构造函数。默认构造函数会执行各种导致单元测试上下文中出现问题的操作。
Mockito 应该调用默认构造函数吗?有什么办法可以避免这种行为吗?
这是我创建模拟对象的方法:
ConcreteClassWithComplexDefaultConstructor mockObject = mock(ConcreteClassWithComplexDefaultConstructor.class);
编辑:所以我弄清楚发生了什么。具体类的默认构造函数不会被调用(正如 Luciano 指出的那样)。但是,会调用该类的静态构造函数。据我所知,静态的东西和 Mockito 工作得不是很好,但是有什么方法可以处理这个问题,即以某种方式让它忽略静态构造函数。不过我并没有抱太大希望...
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.
Is Mockito supposed to invoke the default constructor? And is there any way to avoid this behavior?
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,事实证明我错了。 Mockito 使用 CGLib 和 Objenesis 创建对象。如果您点击该链接,它会解释它如何不调用超类构造函数。
使用以下代码可以轻松测试这一点:
Well, it turns out I was wrong. Mockito uses CGLib and Objenesis to create the Object. If you follow that link it explains how it does not call the super class constructor.
This is easily tested with the following code:
不,Mockito 不会调用模拟类的默认构造函数。
No, Mockito doesn't call the default constructor of the mocked class.