How Mocks Help
Making a Difficult Testing Problem Easy with Mockito
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 themSubscriber<T>
, which receives the messages, and can provide back pressure using aSubscription
Subscription
, which contains methods like request and cancelProcessor
, which simply extends bothPublisher
andSubscriber
Java supports this spec, to the point that those interfaces were added to the java.util.concurrent.Flow
class in Java 9.