I'm trying to figure out how mockito is working behind in order to debug. I was wondering for the object with @Mock annotation, when is it initialized? Like, before @Before or after @Before?
And if there're several different constructors, how is mockito determines which constructors to call?
And if I use jmockit @Mocked instead, are there any different answers of the questions above?
Mock objects created with Mockito don't call any constructor or static initializer. (This is achieved through Objenesis in older versions of Mockito, and ByteBuddy in newer versions.) Consequently, all of the fields are uninitialized, and no side effects in constructors happen at all including any exceptions you might see thrown.
In contrast, spy objects do have their constructors called. Mockito will default to calling a no-argument constructor (public or private) if you don't initialize the field, and you can call the constructor of your choice inside the initializer.
The order of @Mock annotation initialization depends on which technique you use to initialize mocks:
MockitoJUnitRunner, mocks are initialized after initializer blocks, constructors, and @Rules, and before any other @Befores as defined in BlockJUnit4ClassRunner.
MockitoRule, mocks are initialized before any @Before methods, but in undefined order compared to other @Rules unless you chain them manually with
MockitoAnnotations.initMocks(), mocks are initialized exactly when you call that method, which is after initializer blocks and rules, and (if you call within a @Before method) in undefined order compared to other @Before methods.