Mocking and test doubles
In short: A mock is a placeholder for a real dependency (database, network, time) in a test. It returns predefined answers and can check whether it was called.
In more detail: Test doubles is the umbrella term for stand-ins: dummy (only fills a parameter), stub (returns fixed answers), fake (simple replacement implementation, for example an in-memory database), spy (remembers calls), mock (verifies expectations about calls).
In Depth
- Why: Tests become fast, run independent of the network and are repeatable. Error cases (timeout, 500 error) can be produced on purpose.
- Mocking time: Instead of the real clock, a fixed clock so deadlines and expiry are testable.
- Limits: Whoever mocks too much only tests themselves. Integration tests with a real database remain important.
- Technique: Dependency Injection makes dependencies exchangeable.
- Tools: Jest/Vitest (
vi.fn()), Mockito (Java), unittest.mock (Python), WireMock.
See also: Unit test, Code coverage