是否应该调用模仿对象的模拟类的默认构造函数? [英] Is mockito supposed to call default constructor of mocked class?

查看:80
本文介绍了是否应该调用模仿对象的模拟类的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个类的Mockito模拟对象,该对象具有一些相当沉重的网络和事务行为,而我不想在我正在编写的当前单元测试中处理它.但是,在实例化模拟对象时,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.

Mockito是否应该调用默认构造函数?有什么办法可以避免这种行为?

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);

所以我知道发生了什么事. IS N'T调用的具体类的默认构造函数(如Luciano所指出的).但是,将调用类的静态构造函数.据我所知,静态的东西和Mockito不能很好地工作,但是有什么方法可以解决这个问题,即以某种方式使其忽略了静态构造函数.我的希望并不高,但是...

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...

推荐答案

好吧,事实证明我错了. 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:

public class Test
  public Test() {
    // Never called.
    System.out.println("Constructor was called.");
  }

  public static void main(String[] args) {
    Test test = mock(Test.class);
  }

这篇关于是否应该调用模仿对象的模拟类的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆