Mocking frameworks are available for virtually all programming languages. While they may differ in their APIs, the underlying idea is the same. Here, I will use Mockito one of the most popular stubbing and mocking libraries for Java. Mockito offers a simple API, enabling developers to set up stubs and define expectations in mock objects with just a few lines of code. (Mockito is an extensive framework. To learn more, take a look at its documentation.)
Mockito is so simple that knowing the following three methods is often enough:
mock(<class>)—Creates a mock object/stub of a given class. The class can be specified by<ClassName>.class.when(<mock>.<method>).thenReturn(<value>)—A chain of method calls that defines the (stubbed) behavior of the method. In this case<value>is returned. For example, to make theallmethod of anissuedInvoicesmock return a list of invoices, we writewhen(issuedInvoices.all()).thenReturn(someListHere).verify(<mock>).<method>—Asserts that the interactions with the mock object happened in the expected way. For example, if we want to ensure that the methodallof anissuedInvoicesmock was invoked, we useverify(issuedInvoices).all().
Let’s dive into concrete examples to illustrate Mockito’s main features and show you how developers use mocking frameworks in practice. If you are already familiar with Mockito.
Leave a Reply