Test Fake
A test double with a working but simplified implementation that takes shortcuts unsuitable for production, such as an in-memory database.
Also known as: Fake, Fake Object, Test Fakes
Category: Software Development
Tags: testing, software-engineering, patterns, quality
Explanation
A test fake is a type of test double that has a working implementation, but takes shortcuts that make it unsuitable for production use. Unlike stubs, which return canned answers, fakes actually process inputs and produce outputs through real logic, just in a simplified way.
The canonical example of a fake is an in-memory database. A production system might use PostgreSQL, but tests can use a simple in-memory data structure (like a HashMap or dictionary) that implements the same repository interface. The fake stores and retrieves data correctly, supports queries, and maintains consistency, but it does not persist data to disk, handle concurrent access, or optimize queries the way a real database would.
Other common examples of fakes include: in-memory message queues replacing production message brokers, local file-based storage replacing cloud storage services, simplified authentication services that accept any credentials, fake email services that store messages in a list instead of sending them, and fake payment processors that always succeed.
Fakes sit at a unique position among test doubles. They require more effort to create than stubs or mocks because they need a working (if simplified) implementation. However, they provide higher-fidelity testing because they process real logic rather than returning pre-programmed responses. This makes them particularly valuable for integration-style tests that need realistic behavior without the overhead of real external systems.
A key consideration with fakes is correctness: the fake must behave consistently with the real implementation for the scenarios under test, or the tests will give false confidence. Some teams maintain a contract test suite that runs against both the fake and the real implementation to ensure behavioral equivalence.
Fakes are sometimes shared across an entire project or organization. A well-maintained fake for a commonly used service (like a database or HTTP client) can eliminate the need for individual tests to create their own stubs and mocks, reducing duplication and improving test reliability.
Related Concepts
← Back to all concepts