Li-Fan Yu Li-Fan Yu - 5 months ago 29
Java Question

Mockito: When is @Mock object get initialized and which constructor it calls

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?

Thank you!


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: