unittest.mock
The mocking library in Python's standard library, which builds mock objects and records how they were called.
In more detail
It provides Mock and MagicMock, patch for swapping names during a test, create_autospec for doubles that match a real signature, and assertion methods such as assert_called_once_with. It is part of Python itself, so it needs no installation.
Example
gateway.charge.assert_called_once_with(1000, "abc")Related terms
- mock — A test double that stands in for a real dependency and checks that the code under test calls it in the expected way.
- autospec — A unittest.mock feature that builds a mock with exactly the same methods and signatures as a real class.
- monkeypatch — Replacing a name inside a module while a test runs, such as swapping a clock function, and restoring it afterwards.
Taught in
- Fakes, Stubs, Mocks And Spies — Automated Testing, TDD & Quality Engineering
- Why Over-Mocking Breeds False Positives — Automated Testing, TDD & Quality Engineering