Skip to content
PythonTesting, Quality, and Packagingbeginner25 min read

Test-Driven Development Basics

Learn the red-green-refactor cycle, write tests before implementation, and improve code without breaking expected behavior.

In this lesson, you will learn

  • ✓Explain test-driven development and the red-green-refactor cycle.
  • ✓Write a failing unittest before implementing a function.
  • ✓Implement the simplest code that satisfies a test.
  • ✓Refactor working code while keeping its tests passing.
  • ✓Use descriptive tests to document expected behavior and boundary cases.

1. What is Test-Driven Development?

Test-driven development, or TDD, is a development approach in which tests guide the implementation of a feature. A test describes a behavior the program must provide. You write that test before writing the production code that satisfies it.

For example, suppose you need a function called apply_discount(price, percentage). You decide that a price of 100 with a discount of 10 percent must produce 90. Before implementing the function, you write a test that checks this requirement.

Initially, the test may fail because the function does not exist yet. That failure is expected at this stage. The purpose is to establish a concrete requirement before implementing the solution.

TDD does not mean writing every possible test for an entire application before writing any code. It usually means working in small, repeated cycles, with each test guiding the next small change.

Write a test for a requirement

Write a test for a requirement
python
import unittest
 
class DiscountTests(unittest.TestCase):
def test_ten_percent_discount(self):
self.assertEqual(apply_discount(100, 10), 90)
Output
The test defines the expected result, but it cannot pass until apply_discount is implemented.

The test uses unittest.TestCase, which you learned in the previous lesson. The method name starts with test_, so unittest recognizes it as a test method. self.assertEqual(actual, expected) checks whether the two values are equal. The function apply_discount has not been defined in this example yet. That is intentional when demonstrating the first TDD step.

Note

A good test describes observable behavior. It should make clear what input is supplied and what result is expected, without depending unnecessarily on the internal details of the implementation.

2. The red-green-refactor cycle

TDD is commonly described using three steps: red, green, and refactor. You repeat these steps as you develop a feature.

RED — Write a test for a requirement that the current implementation does not satisfy. Run the test and confirm that it fails for the expected reason. If the test fails because of a typo or an unrelated setup error, fix that problem instead of treating the failure as useful evidence.

GREEN — Write the smallest reasonable implementation that satisfies the new test. Run the test again. It should now pass. Avoid adding unrelated features or unnecessary complexity at this stage.

REFACTOR — Improve the structure, naming, or duplication in the working code without changing its intended behavior. Run the tests again to check that the improvements have not introduced regressions.

The cycle is iterative. After one test passes, you can identify the next requirement, write another test, and repeat. The goal is to make progress in small, verifiable steps.

Step 1 — RED: write the test first

Step 1 — RED: write the test first
python
import unittest
 
class DiscountTests(unittest.TestCase):
def test_ten_percent_discount(self):
self.assertEqual(apply_discount(100, 10), 90)
 
if __name__ == '__main__':
unittest.main()
Output
The test fails because apply_discount has not been defined.

Save this code in a file named test_discount.py. Run it with python -m unittest -v test_discount.py. At this stage, Python cannot find apply_discount, so the test fails with a NameError. This is an intentional demonstration of the red stage. The test has revealed that the required implementation is missing. In a real workflow, distinguish this expected failure from a test that fails because the test itself is incorrect.

Note

The RED, GREEN, and REFACTOR snippets are successive stages of one example, not three separate programs to combine blindly. The test and implementation must be connected through the same module or an appropriate import.

3. Tests as executable expectations

An executable expectation is a requirement expressed in code that can be checked automatically. For example, self.assertEqual(apply_discount(100, 10), 90) says that a 10 percent discount on 100 must result in 90.

A test is more precise than a vague comment such as 'calculate a discount correctly'. It records a specific input and the result that should follow. When someone changes the function later, the test can be run again to check whether that requirement still holds.

Tests can also document boundary behavior. For a discount function, useful cases might include a zero discount, a full discount, and a zero price. You should decide what inputs are valid and what the function is supposed to do with invalid inputs.

Tests do not prove that a program is correct for every possible input. They provide evidence for the behaviors they check. Their value depends on choosing meaningful cases and making assertions that accurately represent the requirements.

Add more executable expectations

Add more executable expectations
python
import unittest
 
class DiscountTests(unittest.TestCase):
def test_ten_percent_discount(self):
self.assertEqual(apply_discount(100, 10), 90)
 
def test_zero_discount(self):
self.assertEqual(apply_discount(100, 0), 100)
 
def test_full_discount(self):
self.assertEqual(apply_discount(100, 100), 0)
 
def test_zero_price(self):
self.assertEqual(apply_discount(0, 25), 0)
Output
When run with a suitable apply_discount implementation, all four tests pass.

The first test checks an ordinary discount. The second checks that a zero percent discount leaves the price unchanged. The third checks that a 100 percent discount reduces the price to zero. The fourth checks that applying a discount to zero still returns zero. These examples assume the function accepts prices and percentages in the range covered by the tests. They do not define a complete policy for negative prices or percentages outside the range 0 to 100.

Note

A test suite should reflect the actual requirements. If negative prices or percentages above 100 are invalid in your application, define the expected behavior for those inputs and add tests for it.

4. Expanding the test before expanding the implementation

TDD becomes especially useful when requirements evolve. Suppose the discount function must now reject a percentage below 0 or above 100. Rather than changing the implementation immediately, first decide what the function should do and write a test for that behavior.

For this example, the requirement is that invalid percentages raise ValueError. The test can use assertRaises to verify that the exception is raised.

After writing the test, run it and confirm that it fails because the implementation does not yet enforce the requirement. Then update the function to validate the percentage and run the complete test suite.

The exact exception and validation policy depend on the application. TDD does not choose business rules for you; it helps you express and verify the rules you have chosen.

Test invalid percentages

Test invalid percentages
python
def test_negative_percentage(self):
with self.assertRaises(ValueError):
apply_discount(100, -1)
 
def test_percentage_above_100(self):
with self.assertRaises(ValueError):
apply_discount(100, 101)
Output
Both tests pass only when the function raises ValueError for these invalid percentages.

assertRaises(ValueError) checks that the code inside the with block raises the specified exception. If the function returns normally instead, the test fails. These tests describe a new requirement. The original implementation does not enforce it, so the implementation must be updated before these tests can pass. In a complete test module, these methods belong inside a class derived from unittest.TestCase.

Caution

Do not write a test merely to match whatever the current implementation happens to do. First identify the intended requirement, then make the test and implementation agree with that requirement.

5. Good TDD habits and common limitations

Keep each test focused on one behavior. A test with a descriptive name, such as test_zero_discount, helps a reader understand the requirement without first studying the function's implementation.

Run tests frequently, especially after refactoring. A test that passed yesterday may fail after a change to a shared function or dependency.

Avoid testing only the happy path. Include important boundary cases, expected exceptions, and other behaviors required by the application.

Do not make tests depend on execution order or on data left behind by another test. Independent tests are easier to rerun and diagnose.

TDD is a development technique, not a guarantee of perfect software. A test can be wrong, incomplete, or based on an incorrect requirement. Review both the tests and the code they exercise.

Do not confuse refactoring with adding new behavior. During refactoring, preserve externally observable behavior and use the existing tests as a safety net. When behavior must change, express that change through an updated requirement and suitable tests.

Run the test suite

Run the test suite
bash
python -m unittest -v test_discount.py
Output
The unittest runner reports each discovered test and whether it passed or failed.

Save the test class in test_discount.py and ensure the test module can access apply_discount. The -v option requests verbose output, making individual test results easier to see. When all tests pass, unittest reports an overall OK result. If a test fails, read the failure message and traceback to locate the failed assertion or error. Exact timing and summary details depend on the test suite and Python environment.

Note

A green test suite means the tests that ran passed. It does not mean every possible behavior has been tested or that the program has no defects.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Writing the implementation first and calling the process TDD.

Why it happens: TDD begins by writing a test for the desired behavior before implementing it, then follows the red-green-refactor cycle.

Incorrect Approach
script.py
python
Write a test that expects apply_discount(100, 10) to equal 90 before implementing apply_discount.
Correct Solution
script.py
python
In the TDD cycle, write a test for the next requirement first, run it, and then implement the behavior needed to pass it.

Key takeaway: In the TDD cycle, write a test for the next requirement first, run it, and then implement the behavior needed to pass it.

#2 Treating every failing test as a successful RED stage.

Why it happens: A RED stage is useful when the new test fails for the expected reason; a syntax error or broken test setup is not meaningful evidence of missing behavior.

Incorrect Approach
script.py
python
A NameError caused by the intentionally missing apply_discount function is expected in the first stage; a misspelled test method or malformed assertion is not.
Correct Solution
script.py
python
Confirm that the test fails for the intended reason. A syntax error, misspelled name, or broken test setup is not evidence that the requirement has been tested correctly.

Key takeaway: Confirm that the test fails for the intended reason. A syntax error, misspelled name, or broken test setup is not evidence that the requirement has been tested correctly.

#3 Making a large implementation change to pass one small test.

Why it happens: Large changes make it harder to connect the test result to a specific implementation change; make the smallest change that satisfies the test.

Incorrect Approach
script.py
python
Implement the basic percentage calculation before adding unrelated pricing features.
Correct Solution
script.py
python
Prefer the simplest reasonable change that satisfies the current requirement, then continue with the next test.

Key takeaway: Prefer the simplest reasonable change that satisfies the current requirement, then continue with the next test.

#4 Refactoring without rerunning tests.

Why it happens: Refactoring is intended to preserve behavior, and rerunning tests checks that the cleanup did not introduce regressions.

Incorrect Approach
script.py
python
After extracting discount_amount into a variable, rerun all discount tests.
Correct Solution
script.py
python
Run the relevant test suite after refactoring so accidental behavior changes are detected.

Key takeaway: Run the relevant test suite after refactoring so accidental behavior changes are detected.

#5 Assuming passing tests guarantee complete correctness.

Why it happens: Passing tests provide evidence for tested cases, not a mathematical guarantee of correctness for every possible input or environment.

Incorrect Approach
script.py
python
Four passing discount tests do not establish how the function should handle a string price or a negative price.
Correct Solution
script.py
python
Review test coverage, boundary cases, assumptions, and the requirements that have not yet been checked.

Key takeaway: Review test coverage, boundary cases, assumptions, and the requirements that have not yet been checked.

#6 Confusing a test with an implementation.

Why it happens: A test states expected behavior and checks it; the implementation is the code that provides that behavior.

Incorrect Approach
script.py
python
self.assertEqual(apply_discount(100, 10), 90) checks the function but does not implement its calculation.
Correct Solution
script.py
python
A test specifies and checks expected behavior; production code performs the behavior.

Key takeaway: A test specifies and checks expected behavior; production code performs the behavior.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is test-driven development?
Answer:
Test-driven development is an approach in which tests guide implementation. You write a test for a requirement first, make it pass with a small implementation, and then refactor while keeping the tests passing.
Q2:Explain the red-green-refactor cycle.
Answer:
Red means a newly written test fails for the expected reason. Green means the implementation satisfies the test. Refactor means improving the code's structure without intentionally changing its behavior. Tests are rerun throughout the cycle.
Q3:Why should a test fail before the implementation is written?
Answer:
The failure helps establish that the test actually detects the missing behavior. The developer must confirm that the failure is expected rather than caused by an unrelated syntax or setup error.
Q4:What is an executable expectation?
Answer:
It is a requirement expressed as code that can be run and checked automatically. For example, a test can specify that applying a 10 percent discount to 100 must produce 90.
Q5:How does TDD differ from writing tests after implementation?
Answer:
In TDD, tests guide the implementation from the beginning. When tests are written afterward, the implementation already exists and the tests are created later to check it. Both approaches can provide value, but TDD emphasizes small test-first development cycles.
Q6:Does TDD eliminate the need for debugging?
Answer:
No. Tests can reveal defects and help locate unexpected behavior, but tests themselves can be incorrect or incomplete. Debugging and reviewing requirements remain important.
Q7:Why should tests include boundary cases?
Answer:
Boundary cases check behavior at important limits, such as zero or the maximum allowed percentage. They can expose errors that ordinary inputs do not reveal.
Q8:What does refactoring mean when practising TDD?
Answer:
Refactoring improves code readability, organization, or maintainability without intentionally changing its externally observable behavior. The existing tests help detect accidental changes.
Q9:Can all possible program defects be found by passing tests?
Answer:
No. Passing tests establish that the cases checked by those tests succeeded. Defects can remain in untested inputs, untested execution paths, or incorrect assumptions.
Q10:When should you write the next TDD test?
Answer:
After the current test passes and the code is in a good state, identify the next required behavior, write a focused test for it, and repeat the red-green-refactor cycle.

Key takeaways

  • Test-driven development uses tests to guide implementation in small steps.
  • The usual cycle is RED, GREEN, REFACTOR.
  • A failing test is useful only when it fails for the expected reason.
  • Write the simplest reasonable implementation that satisfies the current requirement.
  • Refactor for clarity while preserving intended behavior, and rerun the tests.
  • Include meaningful ordinary, boundary, and invalid-input cases.
  • Passing tests provide evidence about the tested behavior; they do not guarantee a defect-free program.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: