1. Introduction
This article will cover a difference between Mockito.mock() method and @Mock annotation used in Mockito tests. These two were created to do the same thing but there are some differences.
2. Mockito.mock()
vs @Mock
Mockito.mock()
method and @Mock
annotation are doing slightly the same, which is defining a mock object in unit tests. However, there are some differences.
The Mockito.mock()
method allows us to create a mock object of classes and interfaces. The Mockito.mock()
is usually placed in the test set up method annotated with @Before
in JUnit4 or @BeforeEach
in JUnit 5. We called it before each test to create a new fresh mock object.
Let's have a look at an example test that uses the Mockito.mock()
method:
Notice that Mockito.mock()
method supports only raw types, so we added @SuppressWarnings("unchecked")
to ignore IDE warnings on parametrized ArrayList
we used for testing. You don't like it? We neither.
The @Mock
annotation to the rescue. It allows us to define objects more clearly. It is an alternative to the Mockito.mock()
method. Unlike the mock()
method, we need to initialize Mockito annotations in the test class by adding MockitoJUnitRunner
, using MockitoAnnotations.initMocks()
or MockitoJUnit.rule()
- read more about it in Getting started with Mockito .
Let's take a look at the same example but using the @Mock
annotation, instead of mock()
method:
In this code, we used @RunWith(MockitoJUnitRunner.class)
to enable Mockito annotations. Notice that Mock()
reduces the line of code that is needed to configure a mocked object.
4. Conclusion
In this article, we presented briefly how to use the method and annotation for creating a mock object used in unit tests. Both methods are doing the same, but it is nice we can choose our preferred way, however, the @Mock
annotation looks natural and it increases the readability of the code.
As ususal, Snippets used in this article are available for downloading under the GitHub repo.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}