As mentioned in a previous post, I’m using Mockito extensively. It’s a superb framework that helps writing unit test a lot.
Recently, I came across a problem when trying to write a test for a legacy Spring class, that used injection in both constructor and field. In Guice, the class would like like this:
This isn’t an often case, but I can imagine a situation when that would be used.
Trying to test such a class with Mockito can be tricky. It turns out that when using @InjectMocks annotation, Mockito injects mocks only to the constructor, leaving the fields undefined. In order to test it properly, one needs to initialize the class with the constructor parameter and Mockito by hand: