Mockito Annotations
Learn about some of the annotations provided by Mockito to make tests shorter and more readable.
We'll cover the following
There are some Mockito annotations that help minimize the code for creating and injecting mocks. While writing tests, there can be some repetitive statements. We will use annotations provided by Mockito to get rid of the redundant code and make our tests more readable.
@Mock
The @Mock
annotation is used to create a mock without calling the Mockito.mock()
method.
Instead of creating a mock inside every test, we can move this statement outside and use the @Mock
annotation on it. If we create mocks in the following way, we are using repetitive statements in every test:
StudentDao studentDaoMock = mock(StudentDao.class);
Rather than repeating the above statement in every test, we can create the mocks outside the test method using the @Mock
annotation as follows:
@Mock
StudentDao studentDaoMock;
By using the @Mock
annotation, we will create the mock once instead of creating it in every test.
@InjectMocks
This annotation automatically injects a mock object into the object being tested. We have been passing the mock object to the StudentService
object as a constructor argument in the test method as follows:
StudentService studentService = new StudentService(studentDaoMock);
We can do the dependency injection outside the test method and use the @InjectMocks
annotation as follows:
@InjectMocks
StudentService studentService;
The tests become shorter when we remove the create and inject mock steps from the test method. We can further shorten the method by making the total variable inline. For comparison, a test written with and without annotations is shown below:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.