When Mockito’s InjectMocks does not inject mocks

Looking back at the time wasted yesterday while trying to make a trivial functionality work makes me wonder if it was a good idea to begin with…
It all started  (and ended) yesterday while I was mentoring a team on the fine art of Java unit testing.
We’ve decided to use Mockito’s InjectMocks due to the fact that most of the project’s classes used Spring to fill private fields (don’t get me started).
For those of you who never used InjectMocks before – in the Mockito word we can auto-magically initialize and inject mock objects into the class under test. And it’s all done using annotations.
And so if I have the following class:

public class MyClass {

    @Resource
    private INetworkService networkService;

    @Resource
    private IFileService fileService;

    public boolean SomeMethod(){

        // some logic here

        // More logic here

        networkService.Send();

        return true;
    }
}

I can write a test fixture that looks like this:

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

    @Mock
    private INetworkService networkService;

    @Mock
    private IFileService fileService;

    @InjectMocks
    MyClass myClass;

    @Test
    public void testSomeMethod() {
        boolean result = myClass.SomeMethod();

        assertTrue(result);
    }
}

And so the two dependencies (marked with @Mock) would be faked and inserted into MyClass by constructor, property or field injection.
The problem was that we couldn’t get it to work. The mocks were initialized and the class was created – without the dependencies. It took us some time but finally we’ve found the reason: the real class looked something like this – can you spot the difference?

public class MyClass {

    @Resource
    private INetworkService networkService;

    @Resource
    private IFileService fileService;

    private Integer version;

    public MyClass(Integer version) {
        this.version = version;
    }

    public boolean SomeMethod(){
        
        // some logic here

        // More logic here

        networkService.Send();

        return true;
    }
}

Did you see it?
In our real class we had a non-empty constructor which InjectMocks tried to use, but passed null since Integer cannot be mocked by Mockito (it’s a final class). Once Mockito found a constructor to try and to use it didn’t even try to inject the two fields (lazy bastard). And so the dependencies inside the MyClass remained null causing a null reference exception to be thrown once used.
It’s not that Mockito guys didn’t do a good job, this behavior is documented – which makes it yet another case of RTFM.
The problem is that the tests who successfully run using this mechanism could one day fail just because someone decided to add another constructor…

Happy coding

5 thoughts on “When Mockito’s InjectMocks does not inject mocks”

  1. > it didn’t even try to inject the two fields (lazy bastard)

    That's by design. Mockito respect constructor creation of an object, if you feel this is wrong there's probably an issue the crafted object, field or property injection is only supported to work with older spring beans or jee beans with fields (now even spring recommends costructor creation).

  2. You're right,
    I didn't say it was not suppose to do that and/or that Mockito had a bug or bad behaviour.
    The fact is that the problem is in the
    production code or rather its design.
    It's a case where on bad design cause confusing behavior – and it took us some time understanding why it's not working.
    I wrote this post to help other confused developers – and not to blame or bash Mockito a tool I use all the time.

  3. That's also why making things magical has some shortcomings 😉
    You cannot raise an error because others may expect this or this to happen. Some people want some additional way to support injection of concrete classes (like Integer). I'm quite mitigated on this one, I don't want mockito to be the “magical test dependency injection” mechanism, and I feel that better design is actually achieved by feeling the pain to use his own API, if mockito does everything a developer won't understand this feeling.
    Anyhow I understand it may confuse people when an error arise.

    Note feel free to propose/submit improvement on documentation or code.

  4. Thanks for advice. In my case I had to place missing mocks in @Before but reason was the same.

    Btw don't you think that introducing a new constructor could be significant enought to skew program output?

  5. I don't think so. The last thing I want is one (or one-hundred) of my tests fail due to a change unrelated to the test. In other words every time a test fail which is not due to a bug or a requirement change makes me waste time on test maintenance without actual value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s