Software Development

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.




Tested using 1.5.9.RELEASE and Java 8.

Download the codes



Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like