100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Software Testing

TDD for a Simple Feature

Walk through a complete red-green-refactor cycle for a realistic feature, from the first failing test to a clean, general implementation.

TDD in PracticeBeginner9 min readJul 10, 2026
Analogies

Applying TDD to a Real Feature

Consider building a shopping-cart discount calculator: apply 10% off when the cart subtotal exceeds $100, otherwise no discount. Rather than writing the whole function up front, TDD breaks this into a sequence of small, verifiable steps, each adding one new fact about the required behavior. You start with the simplest possible scenario, get it passing, then add the next scenario that the current implementation cannot yet handle, letting the design emerge from the accumulated test cases rather than from upfront speculation.

🏏

Cricket analogy: A batting coach builds a player's technique against short-pitched bowling one drill at a time — first balance, then the pull shot, then timing against 140kph — rather than throwing a full match scenario on day one, just as TDD builds the discount feature scenario by scenario.

Step One: The First Failing Test

The first test should cover the case with no discount, since it is the simplest branch of the requirement: applyDiscount(50) should return 50 unchanged. This test will fail initially because applyDiscount does not exist, which is expected and correct. The minimal implementation to pass it is simply return subtotal — no conditional logic is needed yet, because no test has demanded it. This might feel like cheating, but it is the discipline: never write code the tests do not yet require.

🏏

Cricket analogy: A net session starts with a bowling machine set to a gentle, predictable line just to confirm the batter's stance and bat swing work at all, before any spin or pace variation is introduced, just as the no-discount case checks the function exists before adding branching logic.

python
# Step 1: RED
def test_no_discount_below_threshold():
    assert apply_discount(50) == 50  # NameError: apply_discount is not defined

# Step 2: GREEN — simplest possible implementation
def apply_discount(subtotal):
    return subtotal

# Step 3: RED again — new scenario the current code can't handle
def test_ten_percent_discount_above_threshold():
    assert apply_discount(150) == 135.0  # fails: still returns 150

# Step 4: GREEN — generalize just enough to satisfy both tests
def apply_discount(subtotal):
    if subtotal > 100:
        return subtotal * 0.9
    return subtotal

Step Two: Triangulating Additional Cases

With the threshold branch added, further test cases sharpen the boundary: what happens exactly at $100 — is the discount inclusive or exclusive of the threshold? A test like apply_discount(100) == 100 forces the condition to be subtotal > 100 rather than >=, closing an ambiguity the requirements might not have stated explicitly. Each new test either exposes a gap in the current implementation or confirms existing behavior, and both outcomes are valuable: the former drives new code, the latter documents an intentional decision.

🏏

Cricket analogy: The third umpire checking a run-out at the crease needs a case exactly on the line, not just clearly in or clearly out, to confirm the decision system handles boundary frames correctly, just as testing exactly $100 clarifies the threshold's inclusivity.

Boundary tests (exactly at a threshold, one unit above, one unit below) are among the highest-value tests you can write, because off-by-one errors in conditionals are one of the most common real-world bug sources.

Step Three: Refactor Once Green

Once all scenarios pass, refactor for clarity without changing behavior: extract the magic numbers 100 and 0.9 into named constants like DISCOUNT_THRESHOLD and DISCOUNT_RATE, and consider whether the function name still communicates intent. Because the test suite already covers the no-discount, above-threshold, and boundary cases, you can make these structural changes with confidence — if a refactor accidentally breaks behavior, a test will fail immediately. This is the payoff of the earlier discipline: refactoring stops being a leap of faith and becomes a checked operation.

🏏

Cricket analogy: A team re-arranging its batting order after a winning tournament run does so carefully, trusting the season's results as a safety net that will show immediately if the new order underperforms, just as tests catch a bad refactor.

Never add new behavior during the refactor step. If you notice a missing case while refactoring, write it down, finish the refactor with tests green, then start a fresh red-green cycle for the new behavior.

  • Break a feature into a sequence of small scenarios rather than designing the whole implementation upfront.
  • Start with the simplest scenario and write only enough code to pass it.
  • Each new test should either expose a gap in the current code or confirm intended behavior.
  • Boundary cases (exactly at a threshold) are high-value tests that catch off-by-one errors.
  • Refactor only once all tests are green, and keep behavior unchanged during refactoring.
  • Extract magic numbers and improve naming once the safety net of passing tests exists.
  • Never add new behavior during a refactor step — capture it as a new test instead.

Practice what you learned

Was this page helpful?

Topics covered

#SoftwareTesting#TestingTDDStudyNotes#SoftwareEngineering#TDDForASimpleFeature#TDD#Simple#Feature#Applying#Testing#StudyNotes#SkillVeris