Test-Driven Development: Tests as Design Feedback

In test-driven development (TDD), you build software through small cycles in which an automated test precedes the production change it motivates. The test describes one required behavior, the implementation makes that behavior work, and a later cleanup improves the structure. You encounter this approach when developing a function or extending an existing feature and want concrete feedback after each small decision.

Start with one observable behavior

Begin with a short list of behaviors the software should support. Select one small item and express it as an executable example. Identify the input, the expected result, and how the test will compare the two. An assertion makes that comparison explicit.


Determine the expected result from the requirement, independently of the implementation. Copying the program's current output into a test can preserve a mistake instead of detecting it. A useful test says what the program should do, rather than merely recording what it happens to do.


Writing the test first also makes you consider the interface. You must decide how another piece of code supplies information and receives a result before choosing the internal algorithm.


Example: A title-formatting function should turn "winter rain" into "Winter Rain". A test can check that returned text without requiring a particular loop, helper function, or internal variable name.



Move through red, green, and refactor

The governing workflow is:


Red→Green→Refactor→next behavior\text{Red} \rightarrow \text{Green} \rightarrow \text{Refactor} \rightarrow \text{next behavior}


During red, run the new test and inspect its failure. The failure should demonstrate the missing behavior. A misspelled import or broken test setup needs attention before you can use the result as evidence about that behavior.


During green, make a simple production change that satisfies the new test while keeping earlier tests passing. Avoid adding speculative features. A small initial implementation can be temporary: another carefully chosen test may show why it needs to become more general.


Refactoring changes code structure while preserving its observable behavior. Once the tests pass, consider clearer names, reduced duplication, or a simpler organization. Make a useful improvement when one is warranted, then run the tests again. You do not need to force a structural change in every iteration.


Stage

Main question

Evidence to seek

Red

Does the example expose missing behavior?

An understood failure

Green

Does the required behavior now work?

New and existing tests pass

Refactor

Can the structure be clearer?

Required behavior stays unchanged


Three stages form a repeating cycle from Red to Green to Refactor.


Interpret the feedback carefully

A new test that immediately passes may describe behavior already supported, or it may fail to check what you intended. Inspect it before deciding what to do next. Do not deliberately damage correct production code just to obtain a failure.


A passing test suite supports confidence in the checked examples; it does not prove every possible input is handled correctly. Choose later examples that challenge assumptions in the current implementation. Thresholds, empty inputs, and limits are useful when the requirement includes them.


Tests should generally observe required results rather than incidental internal arrangements. A test that requires a private helper to have a particular name can obstruct a harmless cleanup. Conversely, changing a required result is a behavior change even if existing tests miss it.



Separate making behavior work from improving its structure. This separation makes the purpose of each edit easier to assess.

What to remember

  • Choose one small behavior and establish its expected result independently.
  • Observe and understand the new test's failure before implementing the behavior.
  • Make the new and existing tests pass.
  • Refactor when useful, preserving required behavior and rerunning the tests.
  • Use later tests to challenge assumptions that earlier examples did not check.

Example: Develop a Postage Calculator in Small Steps

A parcel service charges 350 cents for a package weighing up to and including 1000 g. Each additional started block of 500 g costs 90 cents. The function postage(mass_g) accepts a non-negative integer mass in grams and returns an integer charge in cents. Input validation is outside this task.


The test oracle is the independently established expected result against which a test checks the program. Here, derive expected charges from the pricing rule. The existing assertion is assert postage(1000) == 350, and the current implementation is:


Python
def postage(mass_g):
    return 350


For a mass mm, the pricing rule is:


P(m)=350+90⌈max⁡(0,m−1000)500⌉.P(m)=350+90\left\lceil\frac{\max(0,m-1000)}{500}\right\rceil.


The ceiling counts every started additional block as a whole block.


a) Add a test for a 1200 g package. Establish red, then give a simple implementation that makes both current assertions pass.


First calculate the expectation independently. The mass above the included allowance is ________, found by subtracting 1000 g from 1200 g. This occupies ________ additional started block because any positive fraction of a block is charged as a whole block.


P(1200)=350+90⌈200500⌉=350+90(1)=440 cents.P(1200)=350+90\left\lceil\frac{200}{500}\right\rceil =350+90(1)=440\ \text{cents}.


Write the new assertion before changing production code:


Python
assert postage(1200) == 440


Run it against the current implementation. It returns 350 cents, so the assertion fails because the additional-block behavior is missing. This is the intended red result.


A small first change is:


Python
def postage(mass_g):
    if mass_g > 1000:
        return 440
    return 350


Rerun the assertions for 1000 g and 1200 g. They now return 350 cents and 440 cents, respectively. This implementation is deliberately limited; passing these two examples does not establish the full pricing rule.


The expected charge for 1200 g is 440 cents, and both current assertions pass after the change.


b) Add a test for a 2100 g package. Use its failure to replace the temporary implementation with one that calculates the number of additional blocks.


The mass above the allowance is ________, found from 2100 g minus 1000 g. Dividing by 500 g per block gives 2.2 blocks, so the billable number of additional blocks is ________.


P(2100)=350+90⌈1100500⌉=350+90(3)=620 cents.P(2100)=350+90\left\lceil\frac{1100}{500}\right\rceil =350+90(3)=620\ \text{cents}.


Add the assertion and run it before changing the implementation:


Python
assert postage(2100) == 620


The temporary implementation returns 440 cents, so this test exposes its assumption that every overweight package needs only one additional block.


For a non-negative integer excess mass, adding 499 before integer division by 500 implements the required upward rounding. The integer division therefore produces the number of started blocks.


Python
def postage(mass_g):
    excess_g = max(0, mass_g - 1000)
    blocks = (excess_g + 499) // 500
    return 350 + 90 * blocks


Rerun all three assertions. The calculated charges are 350 cents for 1000 g, 440 cents for 1200 g, and 620 cents for 2100 g.


The expected charge for 2100 g is 620 cents, and the implementation now calculates additional blocks rather than assuming there is exactly one.


c) Extract the started-block calculation into a private helper. State what must stay unchanged and verify the three existing examples.


Begin from the passing implementation. The extraction should make the rounding operation easier to read while preserving the required charge for every valid input. It should not change the allowance, block size, or price.


For non-negative integer amounts and a positive integer block size, the upward-rounded block count is:


blocks=⌊amount+size−1size⌋.\text{blocks}=\left\lfloor\frac{\text{amount}+\text{size}-1}{\text{size}}\right\rfloor.


Extract that expression without changing the pricing calculation:


Python
def _started_blocks(amount, size):
    return (amount + size - 1) // size

def postage(mass_g):
    excess_g = max(0, mass_g - 1000)
    blocks = _started_blocks(excess_g, 500)
    return 350 + 90 * blocks


For 1000 g, the helper receives zero and returns zero blocks, giving 350 cents. For 1200 g, it receives 200 and calculates 699//500=1699 // 500=1, giving 440 cents. For 2100 g, it receives 1100 and calculates 1599//500=31599 // 500=3, giving 620 cents.


Rerun the same assertions without changing their expected values. The extracted expression is algebraically the same as the previous calculation, and the public results remain 350 cents, 440 cents, and 620 cents. All 3 existing assertions pass; their passing results support these examples, while the unchanged expression explains why the extraction preserves the calculation throughout the stated input domain.

A developer has selected one missing behavior and plans to extract a duplicated calculation into a private helper after implementing it. Arrange these actions into one TDD iteration. Assume each implementation change succeeds and no unexpected failures occur.

  1. 1.

    Write one executable test for the selected missing behavior.

  2. 2.

    Extract the duplicated calculation into a private helper without changing required behavior.

  3. 3.

    Make a simple production change that implements the selected behavior.

  4. 4.

    Run the tests again to check that the structural change preserved the tested behavior.

  5. 5.

    Run the new and existing tests and confirm that they all pass.

  6. 6.

    Run the new test and confirm that its assertion fails because the behavior is missing.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A test double is an object that replaces a real object used by the code during a test. While preparing the next Test-Driven Development test, you discover that an invoice service constructs its own payment client, forcing the test to contact a live server.


You propose changing the service constructor to accept a payment-client object. Production would supply the real client, while tests would supply a double that returns controlled responses and records requests.


The general design technique of supplying a required object from outside, rather than constructing it internally, is called .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A stock-management module named inventory already contains available(stock, held), which currently returns zero. Its requirement is to return stock minus held units. A developer writes this test before changing the implementation:


Python
from invetory import available

def test_available_stock():
    assert available(7, 2) == 5


The test run stops with ModuleNotFoundError because the import name is misspelled. What is the best next action in the TDD cycle?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice