Unit testing with mocks

Let's start with understanding what mocking is. Mocking is creating objects that simulate the behavior of real objects. In the previous example, in the unit test, we would want to simulate the behavior of DataService.

Unlike stubs, mocks can be dynamically created at runtime. We will use the most popular mocking framework, Mockito. To understand more about Mockito, we recommend the Mockito FAQ at https://github.com/mockito/mockito/wiki/FAQ.

We will want to create a mock for DataService. There are multiple approaches to creating mocks with Mockito. Let's use the simplest among them--annotations. We use the @Mock annotation to create a mock for DataService:

    @Mock     private DataService dataService;

Once we create the ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.