mockito 是否应该调用模拟类的默认构造函数?

发布于 2024-12-01 09:49:11 字数 497 浏览 0 评论 0原文

我正在尝试创建一个类的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雅心素梦 2024-12-08 09:49:11

好吧,事实证明我错了。 Mockito 使用 CGLib 和 Objenesis 创建对象。如果您点击该链接,它会解释它如何调用超类构造函数。

使用以下代码可以轻松测试这一点:

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

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

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);
  }
慵挽 2024-12-08 09:49:11

不,Mockito 不会调用模拟类的默认构造函数。

No, Mockito doesn't call the default constructor of the mocked class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文