Mockito is a powerful framework for mocking dependencies and testing Java applications. By using Mockito annotations, we can simplify the process of setting up and mocking dependencies, making it easier to write comprehensive and effective unit tests.
To start using Mockito, we first need to add it as a dependency in our project. If you are using Maven, you can add the following lines to your project's pom.xml
file:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.7.7</version>
<scope>test</scope>
</dependency>
For Gradle, you can add the following lines to your project's build.gradle
file:
testImplementation 'org.mockito:mockito-core:3.7.7'
Make sure to replace 3.7.7
with the latest version of Mockito.
Mockito provides a set of annotations that we can use to simplify the process of creating and injecting mocks. Let's explore some of the commonly used annotations.
The @Mock
annotation is used to create a mock object of a class or interface. Mockito will automatically generate an instance of the mocked class or interface, and we can use it to define the desired behavior of methods.
import org.mockito.Mock;
import static org.mockito.Mockito.when;
...
@Mock
private UserService userService;
In the above example, we are creating a mock object of the UserService
class. We can then use the when
method provided by Mockito to define the behavior of different methods of the userService
mock.
The @InjectMocks
annotation is used to automatically inject mocks into the tested object. It tries to match the fields annotated with @Mock
or @Spy
to the fields in the tested object.
import org.mockito.InjectMocks;
...
@InjectMocks
private UserController userController;
In the above example, Mockito will automatically inject the mocks created using @Mock
or @Spy
annotations into the userController
object.
The @Spy
annotation is used to create a spy object. Unlike a mock, a spy object retains the original behavior of the class, but we can still define the desired behavior for specific methods.
import org.mockito.Spy;
import static org.mockito.Mockito.when;
...
@Spy
private UserService userService;
In the above example, we are creating a spy object of the UserService
class. We can then use the when
method provided by Mockito to define the desired behavior of specific methods.
Mockito provides powerful annotations that simplify the process of setting up and mocking dependencies in our unit tests. By using @Mock
, @InjectMocks
, and @Spy
annotations, we can easily create and inject mocks, making it easier to write comprehensive and effective tests. Adding Mockito as a dependency and leveraging its annotations can greatly enhance our unit testing capabilities.
noob to master © copyleft