AdvancedSoftware Engineering · Lesson 12 of 13 · Updated ·
Unit Testing and TDD — Arrange-Act-Assert, Mocks, the Test Pyramid and Red-Green-Refactor
The testing lesson described unit testing as the first level of testing: checking the smallest pieces of a program — single functions or classes — on their own. In real teams, the developer who writes the function also writes its unit tests, as code, and a machine runs all of them on every change. This lesson shows how that works, and how test-driven development (TDD) turns it around by writing the test first.
1. What a unit test looks like
A unit test calls the code with a known input and checks the result automatically. No one reads printouts. Python ships with the unittest module; Java has JUnit, JavaScript has Jest, and the ideas are the same.
Suppose a canteen app calculates a bill: 5% GST is added, and orders of ₹500 or more (before tax) get ₹50 off.
import io
import unittest
def bill(amount):
if amount < 0:
raise ValueError('amount cannot be negative')
if amount >= 500:
amount -= 50
return round(amount * 1.05, 2)
class TestBill(unittest.TestCase):
def test_small_order_gets_only_gst(self):
# Arrange
amount = 200
# Act
total = bill(amount)
# Assert
self.assertEqual(total, 210.0)
def test_discount_starts_exactly_at_500(self):
self.assertEqual(bill(500), 472.5)
def test_negative_amount_is_rejected(self):
with self.assertRaises(ValueError):
bill(-10)
suite = unittest.TestLoader().loadTestsFromTestCase(TestBill)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print('ran', result.testsRun, 'tests;', 'failures:', len(result.failures), 'errors:', len(result.errors))
ran 3 tests; failures: 0 errors: 0
(Normally you just run python -m unittest in the project folder and it finds every test_* method. The last three lines here only run the tests inside this one example.)
Notice the shape of each test — Arrange, Act, Assert (AAA):
| Step | What you do | In the first test |
|---|---|---|
| Arrange | set up the input and objects | amount = 200 |
| Act | call the code being tested — once | bill(amount) |
| Assert | check the result | assertEqual(total, 210.0) |
The second test is a boundary value (₹500 exactly), and the third checks an error path. Good unit tests come from the same test-design techniques as manual testing.
2. When a test fails
Now imagine someone "cleans up" the code and writes > instead of >=:
import io
import unittest
def bill(amount):
if amount > 500: # bug: should be >=
amount -= 50
return round(amount * 1.05, 2)
class TestBill(unittest.TestCase):
def test_small_order(self):
self.assertEqual(bill(200), 210.0)
def test_discount_starts_exactly_at_500(self):
self.assertEqual(bill(500), 472.5)
suite = unittest.TestLoader().loadTestsFromTestCase(TestBill)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
for test, trace in result.failures:
print('FAILED:', test.id().split('.')[-1])
print(trace.strip().splitlines()[-1])
FAILED: test_discount_starts_exactly_at_500
AssertionError: 525.0 != 472.5
The failure names the test and shows expected vs actual. This is the main value of unit tests: a regression (an old feature broken by a new change) is caught in seconds, on the developer's machine, before it reaches a user. In a CI pipeline (Continuous Integration — a server that builds and tests every commit), a failing test blocks the merge.
3. Mocks and stubs: testing one unit alone
A unit test must not send real SMS messages, charge real cards or depend on the internet. Those parts are replaced by test doubles:
| Double | What it does | Example |
|---|---|---|
| Stub | returns fixed answers | a fake exchange-rate service that always says 83.0 |
| Mock | also records how it was called, so the test can check it | did we call send_sms once, with this number? |
| Fake | a simple working version | an in-memory list instead of a real database |
from unittest.mock import Mock
def remind_defaulters(students, sms):
for name, phone, due in students:
if due > 0:
sms.send(phone, f'Dear {name}, fee of Rs {due} is due')
sms = Mock()
remind_defaulters([('Ravi', '98000', 2500), ('Neha', '97000', 0)], sms)
print(sms.send.call_count)
print(sms.send.call_args)
1
call('98000', 'Dear Ravi, fee of Rs 2500 is due')
The mock proves the function messaged only Ravi, with the right text — and no SMS was sent. Passing sms in as a parameter is dependency injection (see the SOLID lesson); code written that way is easy to test.
4. The test pyramid
- Unit tests (bottom): many, run in milliseconds, pinpoint the broken function.
- Integration tests (middle): check that modules work together — your code with a real database or API.
- End-to-end (E2E) tests (top): drive the whole app like a user, for example with a browser tool such as Selenium or Playwright. Valuable but slow and fragile, so keep them few.
A team that has mostly E2E tests and few unit tests has an "ice-cream cone" — slow feedback and failures that are hard to locate.
5. Test-driven development (TDD)
In TDD you write the test before the code, in a short cycle repeated many times:
- Red — write a small test for behaviour that does not exist yet. Run it; it must fail.
- Green — write the simplest code that makes it pass.
- Refactor — improve the code (names, duplication) while keeping all tests green.
Example: a is_leap(year) function. Rule: divisible by 4, except centuries, except centuries divisible by 400.
| Cycle | Test added (Red) | Code that makes it pass (Green) |
|---|---|---|
| 1 | is_leap(2024) is True, is_leap(2023) is False | return year % 4 == 0 |
| 2 | is_leap(1900) is False | return year % 4 == 0 and year % 100 != 0 |
| 3 | is_leap(2000) is True | add or year % 400 == 0 |
def is_leap(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
checks = {2024: True, 2023: False, 1900: False, 2000: True}
for year, expected in checks.items():
assert is_leap(year) == expected, year
print('all', len(checks), 'checks pass')
all 4 checks pass
Each new test forced one more piece of the rule into the code, and every earlier test kept guarding what already worked. Benefits of TDD: code is testable by design, requirements get clarified early ("what about 1900?"), and you get a safety net for refactoring. Costs: more time up front and discipline; it fits logic-heavy code better than UI layout.
6. Code coverage
Coverage is the percentage of code that the tests execute (tools: coverage.py for Python, JaCoCo for Java).
- Statement coverage: lines executed. Branch coverage: both the true and false sides of every
iftaken — stronger. - In
bill(), a test with 200 alone never runs the discount lineamount -= 50. A test with 500 is needed for theTrueside of thatif, and a test with a negative amount for the error line. - 100% coverage does not mean bug-free. It shows the code ran, not that the asserts were right or that the boundaries were tested. Use coverage to find untested code, not as a score to chase.
Good unit tests follow FIRST: Fast, Independent (no test depends on another's order or data), Repeatable (same result every run — no real clock, network or random values), Self-validating (pass/fail, no manual reading), Timely (written with the code).
Common mistakes
- Tests that print results instead of asserting them. A test must decide pass or fail by itself.
- Tests that call a real payment gateway, email server or the internet. Use mocks or fakes.
- Several unrelated checks in one huge test. When it fails you cannot tell what broke.
- Thinking TDD means "write all tests first, then all code". It is one small test at a time.
- Treating 100% coverage as proof of correctness.
Quick recap
- A unit test checks one small unit automatically; structure it as Arrange, Act, Assert.
- Failing tests catch regressions early; CI runs them on every commit.
- Stubs return fixed answers; mocks also record calls; fakes are simple working versions.
- Test pyramid: many unit tests, fewer integration tests, few E2E tests.
- TDD: red → green → refactor, in small steps. Coverage finds untested code but does not prove correctness.