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
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
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
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is test-driven development?
Q2:Explain the red-green-refactor cycle.
Q3:Why should a test fail before the implementation is written?
Q4:What is an executable expectation?
Q5:How does TDD differ from writing tests after implementation?
Q6:Does TDD eliminate the need for debugging?
Q7:Why should tests include boundary cases?
Q8:What does refactoring mean when practising TDD?
Q9:Can all possible program defects be found by passing tests?
Q10:When should you write the next TDD test?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: