DevPath
Tracks

Testing: Unit, Integration, and Test Doubles

What good tests look like, the test pyramid, unit versus integration tests, stubs, fakes and spies, and a TDD loop, shown with unittest and node:assert.

beginner40 min#testing#unit-tests#tdd#mocks#fakes#test-pyramid

Prerequisites: Recursion

Why it matters

Code you cannot safely change is code that rots. Tests are the safety net that lets you refactor, upgrade a dependency, or fix a bug on Friday without fear. They also work as executable documentation: a test names a behavior and proves it. Teams with good tests ship faster, not slower, and interviewers increasingly ask "how would you test this?" after every solution.

Intuition

A test is a tiny experiment with three parts. Arrange the situation, act by calling the code, assert the outcome you expect. If the assertion fails, the code or your expectation is wrong, and either way you learned something in milliseconds instead of from a customer.

Think of a smoke detector. A good one is cheap, sits everywhere, goes off when there is a real problem, and stays silent otherwise. A test that fails randomly or fails whenever you rename a private variable is a smoke detector that cries wolf; people start ignoring it.

How it works

The test pyramid.

        /\        few    end-to-end: real browser, real services; slow, brittle
       /  \
      /----\      some   integration: several real parts together (code + database)
     /      \
    /--------\    many   unit: one function or class in isolation; fast, precise
  • Unit tests check one piece in isolation. They run in milliseconds, so you can run thousands on every save.
  • Integration tests check that real pieces cooperate: your query against a real database, your handler against a real router. Slower, but they catch wiring bugs units cannot.
  • End-to-end tests drive the whole system like a user. Keep a few for critical journeys.
End-to-end testsfew: slow, brittle, whole system
Integration testssome: real parts together
Unit testsmany: fast, precise, isolated
The pyramid is about proportion: most tests sit at the cheap, fast bottom, and only a few expensive ones sit on top.

Test doubles replace a real collaborator (payment gateway, email service, clock) so a test is fast, deterministic, and safe. Vocabulary people mix up:

  • Dummy: passed in but never used.
  • Stub: returns canned answers ("always declines").
  • Fake: a working lightweight implementation (an in-memory database).
  • Spy: records how it was called so you can assert on it afterward.
  • Mock: pre-programmed with expectations that it verifies itself.
Production
Checkout test
Checkout
Checkout
Real payment gatewaynetwork, real money
FakeGatewayrecords charges, canned answer
Same Checkout code, different collaborator. Because the gateway is injected, the test swaps in FakeGateway and stays fast, deterministic, and free of side effects.

To use doubles, code needs dependency injection: receive the collaborator as a parameter instead of creating it inside. That is a design benefit of testing: hard-to-test code is usually tightly coupled code.

Qualities of a good test (a handy mnemonic is FIRST):

  • Fast and Independent: no test depends on another's leftovers or on running order.
  • Repeatable: same result every time. Control time, randomness, and the network.
  • Self-checking: pass or fail without a human reading output.
  • Timely (or thorough): cover edge cases such as empty input, zero, boundaries, and errors.

Test behavior, not implementation. If you refactor internals without changing behavior, tests should stay green.

TDD (test-driven development) is a loop: write a failing test (red), write the simplest code to pass (green), clean up with the tests as protection (refactor). It forces you to design the interface from the caller's point of view and guarantees every line has a reason.

Redwrite a failing test
Greensimplest code to pass
Refactorclean up, tests stay green
Next test
One lap of the TDD loop takes minutes. After refactor you start again with the next failing test.
OperationTimeNotes
Unit test~1 msRun on every save
Integration test~10-500 msReal database or file system
End-to-end testsecondsBrowser plus services; keep few
Cost of a bug found late10x-100xRule of thumb: cheaper at the unit level

Code: testing with a spy and a stub

A Checkout class charges a payment gateway. It receives the gateway as a parameter, so tests can pass a fake that records charges and can be told to approve or decline. Python uses unittest, run programmatically with its output captured so only a summary line prints. JavaScript uses node:assert with a tiny runner.

import io
import unittest
 
 
class Checkout:
    def __init__(self, gateway):
        self.gateway = gateway  # injected dependency
 
    def pay(self, items):
        total = sum(price * qty for price, qty in items)
        if total == 0:
            raise ValueError("empty cart")
        return "paid" if self.gateway.charge(total) else "declined"
 
 
class FakeGateway:
    def __init__(self, approve=True):
        self.approve = approve
        self.charges = []  # spy: remembers every call
 
    def charge(self, amount):
        self.charges.append(amount)
        return self.approve  # stub: canned answer
 
 
class CheckoutTests(unittest.TestCase):
    def test_charges_the_total(self):
        gw = FakeGateway()
        result = Checkout(gw).pay([(250, 2), (100, 1)])
        self.assertEqual(result, "paid")
        self.assertEqual(gw.charges, [600])
 
    def test_declined_card(self):
        self.assertEqual(Checkout(FakeGateway(approve=False)).pay([(100, 1)]), "declined")
 
    def test_empty_cart_never_charges(self):
        gw = FakeGateway()
        with self.assertRaises(ValueError):
            Checkout(gw).pay([])
        self.assertEqual(gw.charges, [])
 
 
suite = unittest.defaultTestLoader.loadTestsFromTestCase(CheckoutTests)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print(f"tests run: {result.testsRun}, failures: {len(result.failures) + len(result.errors)}")

Both versions print tests run: 3, failures: 0. In day-to-day work you would run python3 -m unittest or node --test and let the runner format results; capturing it here just keeps the printed output deterministic (the real runner prints elapsed time).

Notice what each test pins down. One verifies the money amount (via the spy), one the declined branch (via the stub), and one an edge case plus a side effect that must not happen.

Common pitfalls

  • Testing implementation details: asserting that a private helper was called makes refactoring painful. Assert on outputs and observable effects.
  • Flaky tests: caused by real time, randomness, shared state, ordering, or network. Inject a clock, seed random numbers, and isolate state.
  • Tests that depend on each other: one test must not need another to run first.
  • Several unrelated assertions per test: when it fails, you do not know which behavior broke. Name tests after one behavior.
  • Chasing 100 percent coverage: coverage shows what ran, not what was verified. A test with no assertions gives coverage and zero safety.
  • Skipping the edge cases: empty, one item, maximum, negative, duplicates, and error paths are where bugs live.
  • Never seeing a test fail: a test that has never been red might not test anything. Break the code once to confirm it notices.

Practice

Write the edge-case tests easy

Hint

Think of the smallest, the biggest, and the weirdest input.

Show solution

For average(numbers), test a normal list, a single item, an empty list (decide: raise or return None, then pin that choice), negative numbers, and floats where rounding matters (compare with assertAlmostEqual or a tolerance). Each is one small test with a descriptive name.

Make time testable medium

Hint

Pass the clock in rather than calling it inside.

Show solution

A function is_expired(token) calls time.time() internally and cannot be tested without sleeping. Change it to accept now as a parameter, or inject a clock callable that defaults to time.time. In the test pass a fixed value: a token issued at 1000 with a 60 second lifetime is valid at 1059 and expired at 1061. No sleeping, no flakiness.

TDD a FizzBuzz-style function medium

Hint

Red, green, refactor, one behavior at a time.

Show solution

Test 1: fizzbuzz(1) returns "1"; make it pass by returning str(n). Test 2: fizzbuzz(3) returns "Fizz"; add the branch. Test 3: fizzbuzz(5) returns "Buzz". Test 4: fizzbuzz(15) returns "FizzBuzz", which forces you to check 15 before 3 and 5. Refactor safely after each green. The tests drove the order of the branches.

Test a retry wrapper hard

Hint

Use a stub that fails a set number of times, and a fake sleep.

Show solution

retry(fn, attempts, sleep) should call fn up to attempts times, pausing between failures. Test with a stub that raises twice then succeeds (expect 3 calls and the result), one that always fails (expect the final exception after exactly attempts calls), and pass a fake sleep that records delays so you can assert exponential backoff such as [1, 2] without waiting.

Interview questions

  1. Unit versus integration tests? Unit tests isolate one piece with doubles and run fast; integration tests wire real components together and catch interface and configuration bugs.
  2. What is the difference between a mock, a stub, and a fake? Stub returns canned data, fake is a simplified working implementation, mock verifies expected interactions.
  3. How do you test code that depends on time, randomness, or the network? Inject the dependency and substitute a deterministic double.
  4. What makes a test flaky, and how do you fix it? Hidden nondeterminism or shared state; remove the source, never just add retries or sleeps.
  5. Is 100 percent coverage the goal? No. Coverage finds untested code but says nothing about assertion quality. Aim for meaningful behavior and risk coverage.

Interviewers look for: proposing tests before or right after coding, covering edge cases unprompted, explaining how you would isolate dependencies, and balancing the pyramid instead of defaulting to one test type.

Quick check

Your test for a signup email sends a real email through a live provider and sometimes fails when the network is slow. What is the best fix?

Finished this lesson?

Further resources

Related lessons