How to Write Good Unit Tests (With an Edge-Case Checklist You Can Reuse)
What makes a unit test useful rather than noise — structure, naming, testing behaviour not implementation, deterministic tests, parameterised cases, mocking sparingly — plus a reusable checklist of edge cases most bugs hide in.
By Software Side Hustles Editorial Team · Published · Updated · 5 min read
Quick answer: a good unit test checks one behaviour, reads like a specification, fails for exactly one reason and gives the same result every time it runs. Structure it as Arrange, Act, Assert, test the public behaviour rather than private details, and spend most of your effort on edge cases — empty input, boundaries, duplicates, invalid values and time — because that is where bugs live.
The anatomy of a good test
def test_order_total_applies_percentage_discount(): # Arrange order = Order(items=[Item(price=Decimal("20.00"), qty=2)]) # Act total = order.total(discount_percent=10) # Assert assert total == Decimal("36.00")The same in Jest:
test("applies a percentage discount to the order total", () => { const order = new Order([{ price: 2000, qty: 2 }]); // amounts in pence expect(order.total({ discountPercent: 10 })).toBe(3600);});And JUnit 5:
@Testvoid appliesPercentageDiscountToTotal() { var order = new Order(List.of(new Item(new BigDecimal("20.00"), 2))); assertEquals(new BigDecimal("36.00"), order.total(10));}What makes these good:
- The name states the behaviour. When it fails, the test name tells you what broke without reading the code.
- One behaviour per test. Several assertions are fine if they describe one outcome; testing discounts and tax and shipping in one test is not.
- No logic in the test. Loops and conditionals in tests can have bugs of their own. Hard-code the expected value.
- Exact, meaningful values.
36.00derived by hand is better thanassert total > 0.
Test behaviour, not implementation
Tests that check how code works — which private method was called, the order of internal steps — break whenever you refactor, even when behaviour is unchanged. Tests that check what the code does survive refactoring and catch real regressions.
Ask: "If I rewrote this function completely but it still produced correct results, would this test still pass?" If not, it is coupled to the implementation.
The edge-case checklist
Run through this list for any function that takes input. Most production bugs are in one of these rows.
| Category | Cases to try |
|---|---|
| Size | empty, one element, two elements, many, maximum allowed |
| Numbers | zero, negative, one, very large, decimals, NaN/infinity, overflow boundaries |
| Boundaries | exactly at the limit, one below, one above (off-by-one) |
| Strings | empty, whitespace only, leading/trailing spaces, very long, Unicode and emoji, mixed case |
| Collections | duplicates, already sorted, reverse sorted, all identical, unsorted |
| Missing data | None/null/undefined, missing keys, optional fields absent |
| Invalid input | wrong type, malformed format, out-of-range values — does it fail clearly? |
| Time | midnight, month end, leap day, DST change, other time zones, New Year week |
| Money | rounding of halves, many small amounts summed, currency with no minor unit |
| State | first call, repeated call (idempotency), call after an error |
| Concurrency | two operations at once on the same record |
You do not need every row for every function. The habit of asking catches the bugs that "the example works" testing misses. See off-by-one errors and dates and time zones for common examples.
Parameterised tests for many cases
Instead of copying a test ten times, list the cases:
import pytest
@pytest.mark.parametrize("raw, expected", [ ("42", 42), (" 42\n", 42), ("-7", -7), ("0", 0),])def test_parse_quantity_accepts_valid_integers(raw, expected): assert parse_quantity(raw) == expected
@pytest.mark.parametrize("raw", ["", "4.2", "abc", "1e3"])def test_parse_quantity_rejects_invalid_input(raw): with pytest.raises(ValueError): parse_quantity(raw)Jest has test.each, JUnit 5 has @ParameterizedTest with @CsvSource or @MethodSource. Splitting valid and invalid cases into separate tests keeps each test's purpose clear.
Make tests deterministic
A test that sometimes fails ("flaky") is worse than no test: people learn to ignore failures. Common causes and fixes:
- The current time: inject a clock, or freeze time (
freezegun/time-machinein Python,vi.useFakeTimers()/jest.useFakeTimers(),java.time.Clockin Java). - Randomness: inject the random generator or fix the seed.
- Network and external services: replace them with fakes at the boundary; keep real network calls for a smaller set of integration tests.
- Shared state between tests: each test should create its own data; never depend on test order.
- Timing with sleeps: wait for a condition, not for a fixed number of milliseconds.
Mock sparingly
Mocks are useful at boundaries you do not own — HTTP APIs, payment providers, email. Mocking everything inside your own code produces tests that only confirm the code calls what it calls. Prefer real objects for in-process collaborators, simple in-memory fakes (a dictionary-backed repository) over deep mock chains, and a few integration tests against a real database (for example with Testcontainers) for queries.
Coverage is a tool, not a goal
Line coverage tells you which code your tests never run; it cannot tell you whether the tests check anything meaningful. A test with no assertions can reach 100% coverage. Use coverage to find untested branches, then write tests that assert on behaviour. Mutation testing (mutmut, Stryker, PIT) is a stronger signal: it changes your code slightly and checks whether a test fails.
Write the failing test first when fixing a bug
Before fixing a bug, write a test that reproduces it and watch it fail. Then fix the code and watch it pass. This proves the test actually detects the bug, documents the case, and prevents the bug returning. See how to debug code systematically.
Property-based testing
For functions with clear invariants, let a library generate hundreds of inputs: "sorting twice equals sorting once", "decode(encode(x)) == x", "the output is never longer than the input". Hypothesis (Python), fast-check (JavaScript) and jqwik (Java) find edge cases you would not think to write, and shrink failures to a minimal example.
Frequently asked questions
How many tests should a function have?
Enough to cover each distinct behaviour and the relevant edge cases. A simple getter may need none; a pricing function may need twenty.
Should I test private methods?
Usually not directly. Test them through the public behaviour they support. If a private method is complex enough to need its own tests, it may belong in its own unit.
What is the difference between unit and integration tests?
Unit tests check a small piece in isolation and run in milliseconds. Integration tests check that pieces work together — your code with a real database, queue or HTTP layer. You need both.
Where this skill pays off
Writing edge cases that break a plausible solution is one of the most valuable skills in AI code evaluation — and our free merge intervals review tests whether you can confirm that correct code is correct, not only find bugs. Read how to evaluate AI-generated code to see how edge-case hunting fits into paid review work.