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

[wp_ad_camp_1]

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.

[wp_ad_camp_2]

Notice, service2 is null.

How to fix it

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

or

[wp_ad_camp_3]

Example

Tested using 1.5.9.RELEASE and Java 8.

Download the codes

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

[wp_ad_camp_4]

Loading

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