An introduction to mocking frameworks

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 the all method of an issuedInvoices mock return a list of invoices, we write when(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 method all of an issuedInvoices mock was invoked, we use verify(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.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *