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.
| Kind | What it does |
|---|---|
| Dummy | fills in parameters and is not used in the test at all, for example a required argument that does not matter |
| Fake | has a working but simplified implementation, such as an in-memory database instead of a real one |
| Stub | returns canned answers to calls |
| Spy | a stub that also records how it was called |
| Mock | knows 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.
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 mockLibraries 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- Martin Fowler — Test Double (словарь Джерарда Месароша)martinfowler.com/bliki/TestDouble.html(opens in a new tab)
- Martin Fowler — Mocks Aren't Stubsmartinfowler.com/articles/mocksArentStubs.html(opens in a new tab)
- Python — unittest.mock: mock object librarydocs.python.org/3/library/unittest.mock.html(opens in a new tab)
Verified 9 Nov