This article will cover the differences between @Mock and @InjectMocks annotations from the Mockito testing framework. These two exists in a single unit test and allows to create a test object filled with mock classes ready for assertions.
The @Mock annotation marks a field as a mock - a dummy implementation of a real object on which we could define the specific behavior that will take a place after we call particular methods.
Let's consider the following example unit test that uses @Mock annotation to create a mock of a
In this example, we created a mock object and then call the
add(...) method on that object twice.
Mockito.verify(...) was used to verify if that specific method was called two times, with given parameters.
You can see this unit test does not test any exceptional cases. That's why using just mock objects in unit tests doesn't make any sense.
@Mock annotation should always exist in conjunction with
The @InjectMocks annotation creates an instance of the class and injects all the necessary mocks, that are created with the
@Mock annotations, to that instance.
The following sample code shows how @Mock and @InjectMocks works.
Consider we have a
Car and a
As you see, the
Car class needs the
Driver object to
Mockito will mock a
Driver class and configure its behavior using the
when(...).thenReturn(...) notation. Using
@InjectMocks Mockito will put that
Notice that we don't have to initiate the
Car object. Mockito will do that for us.
In this article, we presented two annotations that come with the Mockito framework and are the most common ones. Note that you must use
Mockito.initMocks(this) to initialize these annotations. In JUnit 5 instead of @RunWith, you should use
@InjectMocks exists in conjunction, almost every Mockito unit test will have that pair.
As usual, the code used in this tutorial is available under GitHub repository.