Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 348
Li-Fan Yu Avatar asked Jan 20 '26 11:01

Li-Fan Yu


1 Answers

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:

  • If you use MockitoJUnitRunner, mocks are initialized after initializer blocks, constructors, and @Rules, and before any other @Befores as defined in BlockJUnit4ClassRunner.
  • If you use MockitoRule, mocks are initialized before any @Before methods, but in undefined order compared to other @Rules unless you chain them manually with RuleChain.
  • If you use 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.
like image 185
Jeff Bowman Avatar answered Jan 22 '26 01:01

Jeff Bowman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!