TestingMedium30 XP3 min read
What is the difference between a mock, stub, spy, and fake in testing?
TL;DR: Stub: returns pre-programmed responses. Mock: also verifies interactions (calls made). Spy: wraps real object and records calls. Fake: simplified working implementation (in-memory repo). All are types of test doubles.
Full Answer
| Aspect | Double type | Purpose |
|---|---|---|
| Stub | Returns canned data | Control test inputs |
| Mock | Stub + verifies calls | Assert interactions happened |
| Spy | Wraps real object, records calls | Partially mock while keeping real logic |
| Fake | Working lightweight impl | In-memory database, test clock |
๐ฏ
Prefer fakes for repositories (in-memory list instead of real database). Use mocks only when you need to assert a specific method was called with specific arguments.
Code Examples
dartFake repository vs mock
Output
// Fake: test the behavior through real logic // Mock: test that the right calls were made
Common Mistakes
- โOver-mocking: testing that every private method was called โ brittle and tightly coupled to implementation
- โUsing a mock when a fake would make the test more readable and robust
Interview Tip
๐ก
Cite Martin Fowler's 'Mocks Aren't Stubs' article if you want to impress. The key insight: state-based testing (fakes) is often better than interaction-based testing (mocks).
#mock#stub#spy#fake#test-double