Photo by Glen Carrie on Unsplash

How Mocks Help

Making a Difficult Testing Problem Easy with Mockito

Kenneth Kousen
6 min readFeb 22, 2023

--

Our simple example uses Java, JUnit 5, and the Mockito testing library for creating a mock to verify that an algorithm is implemented properly. It’s based on a similar example found in the Spock Example project, part of the Spock testing library in Groovy.

Project Setup

Consider a classic publisher/subscriber system. A publisher sends messages to each of its subscribers. A subscriber registers with a publisher and provides a callback method that is invoked by the publisher. Developers have been implementing such systems for decades, most recently adhering to the Reactive Streams specification. Implemented in Java, that spec involves only four interfaces:

  • Publisher<T>, which registers subscribers and sends messages to them
  • Subscriber<T>, which receives the messages, and can provide back pressure using a Subscription
  • Subscription, which contains methods like request and cancel
  • Processor, which simply extends both Publisher and Subscriber

Java supports this spec, to the point that those interfaces were added to the java.util.concurrent.Flow class in Java 9.

--

--

Kenneth Kousen

Author of the books Mockito Made Clear, Help Your Boss Help You, Kotlin Cookbook, Modern Java Recipes, Gradle Recipes for Android, and Making Java Groovy