Creating tests using mock objects
In the previous recipe, we used a data fixture file to populate an in-memory database in order to run our tests on predictable and static sets of data. While this makes the tests consistent and deterministic, we are still paying the price of having to create a database, populate it with data, and initialize all the JPA and connectivity components, which could be viewed as an excessive step for a test. Luckily, Spring Boot provides internal support for being able to mock beans and inject them as components in the tests for setup and further use as dependencies within an application context.
Let's examine how we can use the power of Mockito so that we don't need to rely on the database at all. We will learn how to elegantly mock the Repository
instance objects using the Mockito framework and some @MockBean
annotation cleverness.
How to do it...
- First, we will create a new
MockPublisherRepositoryTests
test class in thesrc/test/java/com/example/bookpub
directory...