D
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

AspectDouble typePurpose
StubReturns canned dataControl test inputs
MockStub + verifies callsAssert interactions happened
SpyWraps real object, records callsPartially mock while keeping real logic
FakeWorking lightweight implIn-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