Writing tests in a service using Mockito
In the previous section, we created our unit tests using the H2 database; in this approach, we will completely omit the use of the database and utilize the concept of mocking in creating sample data in our unit tests. We will achieve this by using Mockito. Mockito is a mocking framework in Java that allows us to test classes in isolation; it does not require any databases.
It will enable us to return dummy data from a mocked object or service. Mockito is very useful, as this makes unit testing less complex, especially for larger applications, as we don’t want to test the services and dependencies simultaneously. The following are the other benefits of using Mockito:
- Supports return values: Supports mocking return values.
- Supports exceptions: Can handle exceptions in unit tests.
- Supports annotation: Can create mocks using annotation.
- Safe from refactoring: Renaming method names or changing the order of parameters...