QA AND TEST AUTOMATION · PART 3 · AUTOMATION FUNDAMENTALS · PRACTICE · 33 OF 112

Test-Driven Development (TDD): Red, Green, Refactor

Test-driven development step by step: write a failing test (red), write just enough code to pass (green), then clean up (refactor), in tiny cycles. Built live on ShopRung's free-shipping rule in pytest, with triangulation, what TDD is good and bad at, how ATDD and BDD extend it, and what testers bring to a TDD team.

  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 / 13

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

Key takeaways

  • Red → green → refactor
  • small steps
  • fake it, then triangulate
  • boundaries as examples
  • ATDD and BDD

Notes

The cycle

The cycle has three steps. Red: write one small test for the next behaviour, run it, and see it fail. Green: write the simplest code that makes it pass, even if it is not pretty. Refactor: clean up the code and the test, running the tests after each change so they stay green. Then repeat. Each cycle takes a few minutes. The failing step matters: it proves the test can catch the missing behaviour.

Red, green, refactor
  • RED write one small test for the next behaviour; run it: it must FAIL
  • GREEN write the simplest code that passes
  • REFACTOR clean up code and test, keep everything green
  • repeat, a few minutes per cycle

Red 1

Rule price nine: shipping is free when the subtotal after discount is seventy five dollars or more, otherwise four ninety nine. Start with the simplest case: a ten dollar order pays four ninety nine. Write the test. Run pytest. It fails, because the shipping module does not even exist yet. That is red. Make sure it fails for the reason you expect, not because of a typo in the test.

test_shipping.py
from shipping import shipping

def test_small_order_pays():
    assert shipping(1000) == 499

$ pytest -q
E ModuleNotFoundError: No
  module named 'shipping'
1 error

red: it fails, for a good reason

Green 1

Green: write the simplest code that passes. Return four ninety nine, always. Run the tests: one passed. It looks silly, and that is the point. You only write code a test demands. This step is called fake it till you make it. The next test will force the real logic, and every line of the final code will have a test that needed it.

shipping.py
def shipping(after_discount):
    return 499

$ pytest -q
1 passed

yes, it is "fake it":
the next test will force
the real logic

Red 2

Now add a test that breaks the fake: exactly seventy five dollars ships free. Add its neighbour too, seventy four ninety nine pays. Run them. Free at seventy five fails, assert four ninety nine equals zero. This is called triangulation: each new example forces the code to become more general. And notice what we chose: boundary values. TDD and the test design techniques from Part one fit together perfectly.

Triangulate
def test_free_at_75():
    assert shipping(7500) == 0

def test_pays_at_74_99():
    assert shipping(7499) == 499

$ pytest -q
F test_free_at_75
  assert 499 == 0
1 failed, 2 passed

Green 2

Make it green with the real rule: if the amount is at least seventy five hundred cents, return zero, otherwise the fee. Three passed. Write greater than or equal on purpose, because the boundary test forced it. If you had written greater than, the free at seventy five test would have stayed red, and you would have caught ShopRung's free shipping boundary bug before it ever existed.

shipping.py
FREE_FROM = 7500
FEE = 499

def shipping(after_discount):
    if after_discount >= FREE_FROM:
        return 0
    return FEE

$ pytest -q
3 passed

Red, green 3

Keep a list of behaviours you still need. The requirements say nothing about an empty cart, but charging four ninety nine for nothing is clearly wrong, and ShopRung returns zero. Write the test: shipping of zero is zero. Red. Add the check. Green, four passed. Notice that writing tests first raised a question the requirement missed. In a real team, you would confirm it with the product owner and add it to the rule.

One more rule
def test_empty_cart_is_free():
    assert shipping(0) == 0
# red: 499 != 0

def shipping(after_discount):
    if after_discount == 0:
        return 0
    ...
# green: 4 passed

Refactor

Refactor. The four tests repeat themselves, so merge them into one parameterized test with four rows. The code could also be tidied, perhaps naming the empty cart case. After each small change, run the tests: still four passed. That is the safety net TDD gives you. Refactoring without tests is guessing. With them, you can clean up boldly, because any mistake turns a row red within a second.

Refactor, still green
@pytest.mark.parametrize(
  "amount, fee", [
  (0, 0), (1000, 499),
  (7499, 499), (7500, 0)])
def test_shipping(amount, fee):
    assert shipping(amount) == fee

$ pytest -q
4 passed
tests are code: tidy them too

Why it helps

Why do teams use it? Every line of code has a test that needed it. Code comes out small and easy to test, because hard to test code is painful to write test first. Feedback is fast, refactoring is safe, and unclear rules surface early, like our empty cart. Its limits: it says little about layout or usability, it does not replace exploratory testing, tests can still mirror the code badly, and it takes practice.

Good at / weak at
  • good at every line has a test small, testable design fast feedback, safe refactor finds unclear rules early
  • weak at UI layout, exploratory risk if tests mirror the code needs practice and discipline

ATDD and BDD

TDD can start higher up. In acceptance test driven development, the team agrees on concrete examples for a story before building it, and those examples become automated acceptance tests. Behaviour driven development writes them as given, when, then, like: given a cart of seventy five dollars, when I check out, then shipping is free. Testers are central here, because they are good at finding the examples. Part seven covers BDD with Cucumber.

Beyond unit TDD
  • ATDD: acceptance test-driven development: agree examples for a story first, then build
  • BDD: the same, written as Given / When / Then
  • Scenario: free at $75.00 Given a cart of $75.00 When I check out Then shipping is free

Common mistakes

How TDD goes wrong. Writing ten tests first and then all the code. Skipping red, so you never see the test fail. Taking big steps, fifty lines of code to get green. Skipping refactor, so the mess grows. Testing internals, so every refactor breaks tests. And believing TDD means no testers are needed. Developer tests check what developers thought of. Testers still find what nobody thought of.

Avoid these
  • writing many tests, then code
  • skipping red (never seeing the test fail)
  • big steps: 50 lines to green
  • skipping refactor
  • testing internals, so refactors break tests
  • treating TDD as "no more testers needed"

Say it like this

In the interview: TDD is red, green, refactor. Write a failing test for the next small behaviour, write the simplest code to pass, then clean up while the tests stay green. As a tester, I bring the examples, chosen with partitions and boundaries. It gives fast feedback and safe refactoring, and ATDD and BDD apply the same idea to acceptance examples agreed with the team. Then describe a small real example, like our shipping rule.

In the interview
  • "Red, green, refactor: a failing test for the next
  • behaviour, the simplest code
  • to pass, then clean up with tests green. I pick examples
  • with partitions and boundaries. It gives fast
  • feedback and safe refactors;
  • ATDD and BDD apply it to acceptance examples."

Interview questions

Q1What is test-driven development?

A practice where you write a failing test before the code, write the minimum code to make it pass, then refactor, in short repeated cycles (red, green, refactor).

Q2Why must the test fail first?

To prove it can detect the missing behaviour and is testing the right thing; a test that never fails may test nothing.

Q3What is triangulation in TDD?

Adding further examples that force a fake or hard-coded implementation to become general, such as testing both $74.99 and $75.00.

Q4What are the benefits of TDD?

High test coverage by construction, smaller and more testable designs, fast feedback, safe refactoring and early discovery of unclear requirements.

Q5What are the limitations of TDD?

It does not cover usability, layout or unknown risks, needs discipline, and tests can mirror implementation; exploratory and system testing are still needed.

Q6What is the difference between TDD, ATDD and BDD?

TDD drives code with unit tests; ATDD drives a feature with agreed acceptance tests; BDD expresses those as Given/When/Then behaviour examples in shared language.

Q7What role do testers play in a TDD team?

Suggest examples and edge cases, review developer tests, write acceptance tests, run exploratory testing and cover integration and system levels.

Q8Does TDD replace QA?

No. It improves code-level quality, but integration, system, exploratory, performance and security testing still need dedicated attention.