Bookmarks

Test double

A general name for objects that replace a real component in tests, such as a database, a payment gateway or an HTTP client, so that the test does not depend on it.

Also: double, stunt double, test doubles

checked 9 Nov

All terms

Real dependencies are not needed in tests and are often harmful: a payment gateway takes money, a mail service sends emails, a database needs an environment and is slow. Instead, a double is put into the test: a lightweight substitute that behaves as required. The name refers to the stunt double in films, where another person performs the stunt in place of the actor.

Kinds of doubles

The term was coined by Gerard Meszaros while writing the book xUnit Test Patterns, to avoid confusion between the different names for stand-ins. He identified five kinds, and on 17 January 2006 Martin Fowler retold this classification on his blog.

KindWhat it does
Dummyfills in parameters and is not used in the test at all, for example a required argument that does not matter
Fakehas a working but simplified implementation, such as an in-memory database instead of a real one
Stubreturns canned answers to calls
Spya stub that also records how it was called
Mockknows in advance which calls are expected, and the test verifies that they happened

How mocks and stubs are used

Doubles usually replace external dependencies: the database, the network, the clock. A mock is used for behaviour verification: the test confirms that the code under test called the dependency in the right way. A stub is used for state verification: it only supplies data, and the result is checked on the object itself.

pythonA payment test with a double of the payment gateway
from unittest.mock import Mock gateway = Mock()gateway.charge.return_value = "ok"   # a canned answer, as with a stub service.pay(1000, gateway) gateway.charge.assert_called_once_with(1000)   # a call check, as with a mock

Libraries provide ready-made doubles: unittest.mock in the Python standard library, jest.fn and vi.fn in Vitest for JavaScript, Mockito for Java, gomock for Go. Where no double is available, the substitution is done by hand: write a class with the same interface, or replace a function with a fixture. In pytest, monkeypatch does this.

How it differs from an integration test

With a double, the test checks only its own code. It is fast and predictable, but it does not guarantee that the real gateway or database will accept the same requests. So doubles complement integration tests rather than replace them, since in those tests the components work for real.

Sources

the term is written from these pages

Verified 9 Nov

Not to be confused with

what it is mixed up with and how it differs

  • integration test

    An integration test checks modules together with their real dependencies, while a double replaces a dependency entirely.

In depth in the references

where the topic is covered in detail