0

Using Mockito @InjectMocks with Constructor and Field Injections

There is a scenario to watch out for where we have class with a few instance variables of reference types but not all of them get initialized via a constructor. This post demonstrates shows how we could unknowingly miss initializing other mocks in a class and how to fix them.

Codes to Test with mocks

Without Constructor

Using @Mock, and @InjectMocks work fine as we would expect.

With Constructor

If we initialize one of the instance variables via a constructor, the other instance variable will not be.

Notice, service2 is null.

How to fix it

There is no elegant way to fix. What we can do is explicitly initialized service2.

or

Example

Tested using 1.5.9.RELEASE and Java 8.

Download the codes

https://github.com/Turreta/com-turreta-mockito-injectmocks-constructors-and-fields