问题
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