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...
Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.
Using Moq, I need to create a fake over an existing class (not interface*) that has no default ctor. I can do this using the "traditional" syntax: var fakeResponsePacket = new Mock<DataResponse>( new object[]{0, 0, 0, new byte[0]}); //specify ctor arguments fakeResponsePacket. Setup(p => p.
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().
The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.
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);
}
No, Mockito doesn't call the default constructor of the mocked class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With