Suppose MokeysClass
has a constructor declared like this, where Foo
is some other class.
public MokeysClass(String name, int counter, Foo myFoo)
I would write my test like this.
@RunWith(MockitoJUnitRunner.class)
public class TestArray {
@Mock
private Foo mockMyFoo;
private String nameToInject = "Mokey";
private int counterToInject = 42;
@Spy
private MokeysClass toTest = new MokeysClass(nameToInject, counterToInject, mockMyFoo);
@Test
public void shouldCallMethod() {
toTest.myMethod(true);
verify(toTest).otherMethod();
}
}
so that I am explicitly stating which constructor to call when I create my test object, and what arguments to pass to it.
There are some reasons not to rely on @InjectMocks
to do this step for me, particularly if the class being tested is more complex and has more than one constructor. Mockito chooses the constructor that has the most arguments, but if there are several constructors with the same number of arguments, Mockito could choose any of the constructors; that is, the behaviour is undefined.
Once Mockito has chosen a constructor, it checks whether that constructor can in fact be used for constructor injection. Constructor injection will not be used if
- one or more of the parameters of the chosen constructor is a primitive type,
- the type of one or more of the parameters of the chosen constructor is a final class,
- the type of one or more of the parameters of the chosen constructor is a private class,
- the only constructor of the class is the default constructor.
If any one of these conditions holds, for the constructor that Mockito chose, then constructor injection won’t be used. In this case, the class must have a default constructor, otherwise Mockito will throw an exception.
The complexity of the criteria which Mockito uses when choosing whether to apply constructor injection implies that adding or removing a constructor, or changing the parameters of a constructor, can make Mockito switch from using constructor injection to using setter and field injection; or from using setter and field injection to using constructor injection. This can occur even if the constructor that is changed is not the one that will be used for constructor injection.
As a result, any test that uses constructor injection is automatically quite brittle; in the sense that changes that are not directly related to the test itself can cause the test to fail. Such failures can be difficult to troubleshoot.
The @InjectMocks
annotation was designed for use with frameworks such as Spring that do dependency injection; and for tests of classes that use Spring, it can be invaluable. But if dependency injection is not part of your class, I would strongly recommend avoiding @InjectMocks
on account of its brittleness. You really want your test code to be as easy to maintain and to troubleshoot as your production code is.