10

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

David Nordvall
  • 12,404
  • 6
  • 32
  • 52

2 Answers2

12

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);
  }
Community
  • 1
  • 1
  • 2
    I would add that as a general rule - mock interfaces instead of classes. Implementation may vary, you don't want to change tests just because someone changed some impl behavior. – Bivas Aug 24 '11 at 10:00
  • I would love it if the constructor didn't do anything and if I had an interface instead of a concrete class. That isn't the reality, however, and there's nothing I can do about it. – David Nordvall Aug 24 '11 at 10:37
  • @David If that is the case then the constructor will need to be called *anyway* no matter which way you do it. Have you considered creating another class that is a gateway between your network-heavy class and your real class so that you don't need to deal with the legacy code/library directly? –  Aug 24 '11 at 10:48
  • @Bringer128 Why would it need to be called anyway? Because of the reasons given in Aleksis answer? I'm sure that's correct but it wasn't how I expected a mock to work. I assumed that all implemented behavior would be "mocked away". – David Nordvall Aug 24 '11 at 10:55
  • @David - Everything except the default constructor it seems. –  Aug 24 '11 at 10:57
  • @David I was wrong, sorry. My answer has been changed. Luciano was right all along. –  Aug 24 '11 at 11:13
7

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

Luciano Fiandesio
  • 10,037
  • 10
  • 48
  • 56