Category: Test Doubles And Mocks

  • 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…

  • Spies

    As the name suggests, spies spy on a dependency. They wrap themselves around the real object and observe its behavior. Strictly speaking, we are not simulating the object but rather recording all the interactions with the underlying object we are spying on. Spies are used in very specific contexts, such as when it is much…

  • Mocks

    Mock objects act like stubs in the sense that you can configure how they reply if a method is called: for example, to return a list of invoices when getAllInvoices is called. However, mocks go beyond that. They save all the interactions and allow you to make assertions afterward. For example, maybe we only want the getAllInvoices method to…

  • Stubs

    Stubs provide hard-coded answers to the calls performed during the test. Unlike fake objects, stubs do not have a working implementation. If the code calls a stubbed method getAllInvoices, the stub will return a hard-coded list of invoices. Stubs are the most popular type of simulation. In most cases, all you need from a dependency is for…

  • Fake objects

    Fake objects have real working implementations of the class they simulate. However, they usually do the same task in a much simpler way. Imagine a fake database class that uses an array list instead of a real database. This fake object is simpler to control than the real database. A common example in real life…

  • Dummy objects

    Dummy objects are passed to the class under test but never used. This is common in business applications where you need to fill a long list of parameters, but the test exercises only a few of them. Think of a unit test for a Customer class. Maybe this class depends on several other classes like Address, Email, and so on.…

  • Dummies, fakes, stubs, spies, and mocks

    Before we dive into how to simulate objects, let’s first discuss the different types of simulations we can create. Meszaros (2007), defines five different types: dummy objects, fake objects, stubs, spies, and mocks. Each makes sense in a specific situation.

  • Introduction

    Until now, we have been testing classes and methods that were isolated from each other. We passed the inputs to a single method call and asserted its output. Or, when a class was involved, we set up the state of the class, called the method under test, and asserted that the class was in the…