Is mockito supposed to call the default constructor of the mocking class?

I am trying to create a Mockito class mock object with rather heavy network and transactional behavior, which I do not want to deal with in the current unit test that I am writing. However, it looks like Mockito calls the default constructor for the real class when creating the layout instance. The default constructor performs all sorts of actions that cause problems in the context of this unit test.

Is Mockito supposed to use the default constructor? And is there a way to avoid this behavior?

This is how I create an object layout:

ConcreteClassWithComplexDefaultConstructor mockObject = mock(ConcreteClassWithComplexDefaultConstructor.class); 

EDIT: I realized what was going on. By default, the constructor of a particular class is NOT activated (as Luciano pointed out). However, it calls the static constructor of the class. As far as I know, static things and Mockito don't work very well, but is there any way to handle this, anyway, so that it ignores the static constructor. I have no particular hopes, however ...

+6
source share
2 answers

Well, it turns out I was wrong. Mokito uses CGLib and Objenesis to create an object. If you follow this link, it explains how it calls a non -superclass constructor.

This is easy to verify 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); } 
+6
source

No, Mockito does not call the default constructor for the manufactured class.

+5
source

Source: https://habr.com/ru/post/895730/


All Articles