Is mockito supposed to call default constructor of mocked class?

无人久伴 提交于 2019-12-08 16:30:06

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/7173358/is-mockito-supposed-to-call-default-constructor-of-mocked-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!