Creating and Using Test Doubles in Our Tests

Explore test doubles for isolating the system under test and employing the Arrange-Act-Assert pattern for effective test organization and execution.

We will want to use a test double that is not only able to intercept the calls but also able to send back programmed responses. There are several kinds of test doubles, so let’s look at them and see which works best for us here.

Test doubles are tools we can use to isolate the system or code under test from the rest of the system around it.

Types of test doubles

These tools come in different forms, each useful for different testing scenarios:

  • Fakes: They implement the same functionality as the real dependency. An in-memory implementation of a repository could stand in and take the place of a PostgreSQL implementation so that the test does not rely on any real I/O.

  • Stubs: These are like fakes, but the stub implementation responds with static or predictable responses.

  • Spies: They work like an observable proxy of the real implementation. A spy can be used to report back the input, return values, and the number of calls that it receives. Spies can also help with recording the inputs and outputs that were seen for later use.

  • Mocks: They mimic the real implementation, similar to a fake, but do not provide an alternative implementation. Instead, a mock is configured to respond in certain ways to specific inputs. Then, like a spy, it can be used to assert whether the proper inputs were received, the right number of calls were made, and no unexpected calls or inputs were encountered.

Fakes and stubs can be used when the interaction with the dependency is not important to the test, whereas spies and mocks should be used when the input and responses matter.

Working with mocks

For our unit test, we will use mocks. To create the mocks that we will use, we will use the Testify mocks package. This will provide the mocking functionality, along with the mockery tool, to make generating them a breeze. The mockery tool can be installed with the following command:

Get hands-on with 1400+ tech skills courses.