QA AND TEST AUTOMATION · PART 3 · AUTOMATION FUNDAMENTALS · UNIT · 32 OF 112

Mocks vs Stubs vs Fakes: Test Doubles Explained

How to test code that depends on slow, costly or unpredictable things (a payment gateway, an email service, the clock): the five test doubles (dummy, stub, spy, mock, fake), state versus interaction testing, Mockito and unittest.mock side by side, injecting a clock for expiry rules, and the over-mocking trap. Python examples run with their real results.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Dummy, stub, spy, mock, fake
  • state over interaction
  • inject the clock
  • mock only what you do not own

Notes

The problem

Imagine a checkout that charges a payment gateway, then emails a receipt, and checks coupon expiry against today's date. In a unit test, the real gateway is slow, costs money and may be down. The real email service sends real emails. The real clock changes, so a test about expiry passes today and fails next month. And you cannot make the real gateway decline a card on demand, which is exactly the case you most need to test.

Why not use the real thing?
  • payment gateway: slow, costs money, may be down email: sends real emails
  • clock: today changes, so "expired?" changes
  • database: needs setup, slow
  • and you cannot make the real
  • gateway DECLINE on demand

The idea

A test double is any object that stands in for a real one, like a stunt double in a film. Gerard Meszaros named five kinds. A dummy is passed in but never used. A stub returns canned answers: charge returns true. A spy is a stub that also records how it was called. A mock is set up with expected calls and verifies them. A fake is a working but lighter version, like an in memory database. People often say mock for all five; interviewers like the distinctions.

Five test doubles
  • dummy passed in, never used
  • stub returns canned answers "charge() → true"
  • spy a stub that records how it was called
  • mock expects certain calls and verifies them
  • fake a working light version: in-memory DB

Stubs

A stub controls what the dependency answers. With Mockito in Java, create a mock of the payment gateway interface, then say: when charge is called with order seven and four thousand nine hundred ninety nine cents, return false. Pass it to the checkout, and assert that pay returns false. The card declined case, impossible to produce with a real gateway on demand, is now a one line setup. That is the main power of stubs.

Stub the gateway (Mockito)
PaymentGateway gw =
    mock(PaymentGateway.class);
when(gw.charge(7, 4999))
    .thenReturn(false);

var c = new Checkout(gw, email);
assertFalse(c.pay(7, 4999));

// now "card declined" is a
// one-line test

Mocks

Sometimes the result is a call, not a value. After a successful payment, the checkout must send exactly one receipt email. With Python's unittest mock, make the gateway's charge return true, call pay, then assert that email dot send was called once with Alice's address and the message order seven paid. In the declined case, assert it was not called at all. These three Python tests run and pass in about ten milliseconds.

Verify the email (Python)
gateway = Mock()
gateway.charge.return_value = True
email = Mock()
Checkout(gateway, email).pay(7, 4999)

email.send.assert_called_once_with(
  "alice@shoprung.test",
  "Order 7 paid")
# declined: email.send
#   .assert_not_called()

State vs interaction

There are two styles. State testing checks the result or the new state: the total is forty nine ninety nine. Interaction testing checks the calls: the email service was called with these arguments. Prefer state testing, because it survives refactoring. Use interaction testing when the call itself is the behaviour you care about, like sending an email or charging a card, where there is no other result to look at.

Two styles
  • state testing: check the result or the new state assert total == 4999
  • interaction testing: check the calls made verify(email).send(...)
  • prefer state; verify calls
  • only when the call IS the behaviour (email, payment)

Control time

Time is a dependency too. If code reads the real clock inside, a test about expiry depends on the day you run it. Pass today in instead. Here the coupon check takes the expiry date and today as arguments. Test welcome fifteen on the first of January twenty twenty six: expired. On the thirty first of December itself: still valid, matching ShopRung. In Java, inject a java dot time Clock and use Clock dot fixed in tests. The same goes for random numbers.

Injecting today
def coupon_problem(expires_on,
                   today):
    if expires_on and today >
            expires_on:
        return "This coupon has
                expired"

coupon_problem(date(2025,12,31),
  date(2026, 1, 1))  # expired
# 31 Dec itself → None (valid)
# Java: pass a java.time.Clock

Fakes

A fake is a real, working implementation that takes a shortcut. A fake order repository stores orders in a hash map instead of a database. Unlike a stub, it behaves consistently across many calls: save an order, then find it. Fakes suit tests with several steps, and are shared across many tests. Other common fakes: an in memory message queue, and WireMock for HTTP services, which you will meet in Part four.

A fake repository
class FakeOrders implements
    OrderRepository {
  Map<Long, Order> rows =
      new HashMap<>();
  public void save(Order o) {
    rows.put(o.id(), o); }
  public Optional<Order> find(
      long id) { return Optional
      .ofNullable(rows.get(id)); }
}

Over-mocking

The trap is over mocking. Mock every class and verify every call, and the test becomes a mirror of the code: any refactor breaks it, and bugs in how real parts fit together are never seen. The rule: mock at the edges of your system, the things you do not own or cannot control, like the network, payment providers, email, the clock and randomness. Use real objects for your own simple classes, and cover the joins with integration tests.

The over-mocking trap
  • mock every class, verify
  • every call → test mirrors the code any refactor breaks it real bugs between parts are never seen
  • mock at boundaries you do
  • not own: network, payment, email, clock, randomness

Common mistakes

How test doubles go wrong. Mocking the very class under test. Mocking simple value objects that could just be created. Verifying every call, so tests break on harmless changes. Stubs that drift from the real API, returning shapes the real service never sends; contract tests in Part four guard against that. Leaving the real clock in. And no integration test anywhere that checks the real dependency still works.

Avoid these
  • mocking the class under test
  • mocking value objects and simple classes
  • verify() on every call
  • stubs that never match the real API (drift)
  • real clock in tests
  • no integration test to check the real dependency

Say it like this

In the interview: a stub returns canned data so I can control inputs, like a declined card. A mock also verifies interactions, like exactly one receipt email. A fake is a light working version, like an in memory database. I mock only boundaries I do not own, like payment, email and the network, inject the clock instead of reading it, prefer checking results over calls, and cover the real connections with integration tests.

In the interview
  • "A stub returns canned data
  • so I can control inputs, like
  • a declined card. A mock also verifies interactions, like
  • one receipt email sent. A fake is a light working
  • version, like an in-memory DB.
  • I mock only boundaries I do
  • not own, inject the clock, and cover the joins elsewhere."

Interview questions

Q1What is the difference between a mock and a stub?

A stub provides canned answers to control the test's inputs; a mock is set up with expected calls and verifies the interaction happened.

Q2What is a fake?

A working but simplified implementation of a dependency, such as an in-memory database or repository, used when tests need realistic behaviour across several calls.

Q3What is a spy?

A double (or a wrapper around a real object) that records how it was called so the test can check calls afterwards.

Q4What is the difference between state and interaction testing?

State testing asserts the result or resulting state; interaction testing asserts which calls were made to collaborators. Prefer state unless the call itself is the behaviour.

Q5How do you test code that depends on the current date?

Inject the time source (a java.time.Clock or a "today" parameter) and use a fixed clock or chosen dates in tests.

Q6What is over-mocking and why is it bad?

Mocking most collaborators and verifying every call; tests mirror the implementation, break on refactors and miss integration bugs.

Q7What do you mock in a unit test?

External boundaries you do not own or control: network services, payment providers, email, the clock and randomness, not your own simple classes.

Q8Which libraries do you use for mocking?

Mockito in Java (mock, when/thenReturn, verify) and unittest.mock in Python (Mock, patch, assert_called_once_with); WireMock for HTTP services.