Unit Testing
Write fast, focused, trustworthy unit tests: structure, naming, isolation, test doubles, and designing code so that it can be tested.
Introduction
Unit tests form the base of the pyramid because they are fast, precise, and cheap. A good unit suite runs in seconds, pinpoints the failing behavior, and lets developers change code with confidence. A bad one is slow to write, brittle, and fails whenever anyone refactors.
The difference is mostly in what you test and how isolated the tests are, not in the framework you use.
Learning Objectives
- Define a unit and decide what deserves a unit test.
- Structure tests clearly (arrange, act, assert) and name them to document behavior.
- Use test doubles (stubs, fakes, mocks, spies) appropriately.
- Avoid brittle tests coupled to implementation.
- Design code for testability.
- Use AI to draft unit tests and to review them.
1. What Is a Unit, and What to Test
A unit is a small piece of behavior with a clear interface: a function, a class, or a small cluster of collaborating objects. Choose boundaries so that the test describes behavior a stakeholder would recognize (“rows with an empty body are rejected”), not an internal step.
Unit tests are the right place for:
- Business rules and calculations (validation, deduplication fingerprinting, scoring).
- Parsing and formatting.
- State machines and decision logic.
- Error handling and edge cases that are hard to trigger from outside.
They are the wrong place for verifying database behavior, framework wiring, or network interaction. Those belong at the integration level.
2. Structure: Arrange, Act, Assert
1
2
3
4
5
6
7
8
9
10
def test_rejects_row_with_whitespace_only_body():
# Arrange
row = {"body": " ", "source": "email", "date": "2026-11-02"}
# Act
result = validate_row(row)
# Assert
assert not result.ok
assert result.code == "MISSING_BODY"
Principles:
- One behavior per test. If the name needs “and,” split it.
- Names state the scenario and the outcome:
test_rejects_row_with_whitespace_only_bodybeatstest_validate_3. - Keep arrange small. Builders and fixtures hide irrelevant detail so that the test shows only what matters for this case.
- Assert outcomes, not steps. Check returned values and observable state.
- Parametrize table-driven cases rather than copying tests:
1
2
3
4
5
6
7
@pytest.mark.parametrize("body, expected", [
("", "MISSING_BODY"),
(" ", "MISSING_BODY"),
("x" * 10_001, "BODY_TOO_LONG"),
])
def test_invalid_bodies_are_rejected_with_reason(body, expected):
assert validate_row(make_row(body=body)).code == expected
3. Characteristics of Good Unit Tests
- Fast: milliseconds each, so they run on every save.
- Isolated: no database, network, clock, or file system unless it is the point.
- Deterministic: the same result every run.
- Independent: any order, any subset, in parallel.
- Readable: a failure explains itself.
- Maintainable: survive refactoring that does not change behavior.
4. Test Doubles
When a unit depends on something slow or uncontrollable, replace it with a test double:
| Double | Purpose | Example |
|---|---|---|
| Stub | Returns canned answers | Clock returning a fixed time |
| Fake | Simple working implementation | In-memory repository |
| Mock | Verifies interactions | Asserting an email was “sent” once |
| Spy | Records calls for later checks | Capturing log messages |
Guidelines:
- Prefer fakes and stubs over mocks. Tests that assert exact call sequences break with every refactor.
- Mock at boundaries you own and that are slow or external, not internal collaborators.
- Never mock the unit under test, and be suspicious of tests where mocks outnumber assertions.
- Verify the double matches the real thing with an integration or contract test; otherwise, tests pass against a fiction.
5. Brittle Tests and How to Avoid Them
A brittle test breaks when you change the implementation without changing behavior. Typical causes:
- Asserting on private methods, internal data structures, or exact call order.
- Hard-coded values duplicated from the implementation.
- Over-specified mock expectations.
- Testing through too many layers of setup.
Ask: “If I rewrote this function entirely but kept its behavior, would this test still pass?” If not, test the behavior at a more stable boundary.
6. Designing for Testability
Testability is a design property. Code that is hard to test is usually hard to change.
- Separate pure logic from I/O.
validate_rowtakes data and returns a result; reading files and writing to the database happen elsewhere. - Inject dependencies (clock, repository, random source) instead of reaching for globals.
- Keep functions small with few parameters.
- Return values rather than only causing side effects.
- Avoid hidden state such as module-level mutable variables.
1
2
3
4
5
6
7
# Hard to test: hidden dependency on the real clock
def is_recent(item):
return (datetime.now() - item.received).days < 30
# Easy to test: the clock is injected
def is_recent(item, now):
return (now - item.received).days < 30
7. Test-Driven Development
Test-driven development (TDD) writes a failing test first, then the minimum code to pass it, then refactors:
1
Red -> Green -> Refactor
TDD gives fast feedback, produces testable designs, and guarantees that every test has failed once. It suits well-understood logic. It is less natural for exploratory work, where you may spike first and add tests after. It combines well with AI: you write (or approve) the test, and the assistant proposes the implementation. The test acts as the executable specification the assistant must satisfy.
8. Using AI for Unit Tests
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Act as a careful test engineer. Review the unit tests below for the
function under test.
Function and rules: [paste with requirement]
Tests: [paste]
1. List behaviors in the requirement that no test covers.
2. Identify tests that would still pass if the function were wrong
(weak assertions, mirror tests, over-mocking).
3. Identify tests coupled to implementation details.
4. Suggest additional cases (boundaries, invalid inputs, unusual but
valid inputs) and their expected results; mark uncertain ones.
5. Suggest naming and structure improvements.
Do not rewrite the production code.
Use the assistant to widen coverage of cases and to critique. Keep the decisions about expected behavior in human hands.
9. Practical Exercise
For SignalDesk (or your project):
- Choose two pure-logic units (for example, row validation and fingerprint generation).
- Write unit tests using technique-derived cases from lesson 2, in arrange-act-assert form with descriptive names and parametrization.
- Make at least one unit more testable by injecting a dependency or separating I/O from logic.
- Practice TDD on one new rule (for example, a maximum number of rows per file): write the failing test, see it fail, make it pass, refactor.
- Run the AI review prompt, verify the findings, and apply the valid ones.
- Run the suite in random order and in parallel (where supported) to detect hidden dependencies.
Verification
You are ready to continue when:
- Unit tests run in seconds and need no external services.
- Test names describe scenarios and outcomes.
- No test asserts private implementation details.
- Tests pass in random order.
- You have seen each new test fail for the right reason before it passed.
Key Takeaways
- Unit tests are fast and precise when they test behavior at stable boundaries.
- Prefer fakes and stubs; avoid asserting internal interactions.
- Testable design (pure logic, injected dependencies) benefits more than the tests.
- TDD provides a safety net and an executable specification for AI-generated implementations.
- AI is a good critic of unit tests, but expected behavior is a human decision.
What’s Next?
Units working alone do not guarantee a working system. Next, we test how components behave together: databases, APIs, queues, and module boundaries.