Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 9 of 15

Writing test cases

Choosing what to test: normal cases, edge cases and error cases, equivalence classes and boundary values, the Arrange-Act-Assert structure, table-driven tests, and randomised checks against a trusted reference.

Beginner 10 min read·Lesson 287 of 306 in Python Programming

Learning objectives

  • Choose test cases using equivalence classes and boundaries
  • Structure tests with Arrange-Act-Assert
  • Write table-driven and randomised tests

Definition

A test case is a specific input together with the expected outcome. Good test cases are chosen systematically so that a small number of tests covers the behaviours most likely to contain bugs.

Introduction

Testing every possible input is impossible. Testing the right inputs — the boundaries, the empty cases, the invalid ones — catches most bugs with a handful of tests.

Why it matters

Thoughtful test cases find bugs that random poking misses and keep test suites short enough to maintain.

Detailed explanation

Test normal cases (typical inputs), edge cases (empty, single item, zero, maximum) and error cases (invalid input that should be rejected).

Equivalence classes group inputs that should behave the same way; test one representative from each class (for marks: below 50, 50–74, 75–89, 90–100, invalid).

Bugs cluster at boundaries, so test values on and next to each boundary: 49 and 50, 74 and 75, 0 and 100, and just outside the valid range.

Arrange-Act-Assert gives each test a clear shape: set up the data, perform one action, check the result.

Table-driven tests list (input, expected) pairs and check them in a loop or with pytest.mark.parametrize.

Randomised tests generate many inputs and compare against a trusted reference (such as sorted()) or check properties that must always hold.

Each test should check one behaviour and have a name describing it, such as test_rejects_marks_above_100.

When a bug is found, first write a test that reproduces it, then fix the code.

Syntax

Python
def test_transfer_moves_money():
# Arrange
accounts = {"A": 100, "B": 0}
# Act
transfer(accounts, "A", "B", 40)
# Assert
assert accounts == {"A": 60, "B": 40}
  • Normal, edge and error cases.
  • Test on and around boundaries.
  • Arrange, act, assert.

Code examples

Boundary values

Python
def grade(marks):
if not 0 <= marks <= 100:
raise ValueError("marks must be 0-100")
return "A" if marks >= 90 else "B" if marks >= 75 else "C" if marks >= 50 else "F"
cases = [(0, "F"), (49, "F"), (50, "C"), (74, "C"), (75, "B"), (89, "B"), (90, "A"), (100, "A")]
failures = [(m, exp, grade(m)) for m, exp in cases if grade(m) != exp]
print(len(cases), "cases,", len(failures), "failures")
for bad in (-1, 101):
try:
grade(bad)
print(bad, "accepted?!")
except ValueError:
print(bad, "rejected")
Output
8 cases, 0 failures
-1 rejected
101 rejected

Arrange, act, assert

Python
def transfer(accounts, src, dst, amount):
if amount <= 0 or accounts[src] < amount:
raise ValueError("invalid transfer")
accounts[src] -= amount
accounts[dst] += amount
def test_transfer_moves_money():
accounts = {"A": 100, "B": 0} # arrange
transfer(accounts, "A", "B", 40) # act
assert accounts == {"A": 60, "B": 40} # assert
test_transfer_moves_money()
print("test_transfer_moves_money passed")
Output
test_transfer_moves_money passed

More examples

Randomised tests against a reference

Python
import random
def my_sort(items):
a = list(items)
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
rng = random.Random(1)
for _ in range(200):
data = [rng.randint(-50, 50) for _ in range(rng.randint(0, 20))]
result = my_sort(data)
assert result == sorted(data), data
assert len(result) == len(data)
print("200 random cases passed")
edge_cases = [[], [1], [2, 1], [3, 3, 3], [-1, 0, -1]]
print(all(my_sort(e) == sorted(e) for e in edge_cases))
Output
200 random cases passed
True

Step-by-step explanation

  • Python's sorted() is the trusted reference, so any difference reveals a bug in my_sort.
  • A fixed seed makes the 'random' cases repeatable when a failure needs investigating.
  • Hand-picked edge cases complement random ones: empty, single, reversed, duplicates and negatives.

Expected output

Running “Randomised tests against a reference” prints exactly:

TextOutput
200 random cases passed
True

Practical applications

  • Banking software tested at limits such as zero balances and maximum transfers.
  • Property-based testing libraries such as Hypothesis.

Best practices

  • Cover normal, edge and error cases.
  • Test boundaries on both sides.
  • Name tests after the behaviour they check.

Common mistakes

Only testing the happy path

Avoid

assert grade(85) == "B" # the only test

Prefer

Test 0, 49, 50, 74, 75, 89, 90, 100, -1 and 101 too.

Bugs hide at boundaries and in invalid input.

Important notes

  • Code coverage tools show which lines your tests never run, hinting at missing cases.

Key takeaways

  • Choose cases with equivalence classes and boundaries.
  • Structure tests as arrange-act-assert.
  • Use tables and randomised reference checks.

Try it yourself

  1. 1
    Design test cases for a function that validates Indian PIN codes (6 digits, not starting with 0).
  2. 2
    Write a randomised test comparing your own max function with Python's max.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedA function accepts marks from 0 to 100. Which inputs best test the boundaries?
Practise this topic