To design unit tests, start by writing one failing check for a specific behavior, run it, then make it pass and refactor. Each test should call a single unit with controlled inputs, assert on observable outputs, and finish in milliseconds. The key condition is isolation: if a test needs a network, a database, or the current clock to behave a certain way, you've moved past unit testing. Everything below expands that core loop into a repeatable design process—what counts as a unit, how to pick cases that actually catch bugs, how to handle dependencies without turning tests into brittle mirrors of your code, and how to keep a suite useful as it grows.
What a Unit Test Is—and What It Isn't
A unit is the smallest piece of code you can reason about on its own: usually a function, a method, or a small class with a single responsibility. A unit test exercises that piece directly and checks a result. It runs in isolation from other tests, from the file system if possible, and from external services. It's fast—most unit tests finish in single-digit milliseconds—so you can run thousands of them on every save.
That speed and isolation are the whole point. They let you find the exact line that broke within seconds of a change. Two other kinds of tests get confused with unit tests, and the distinction matters for design.
Integration tests check how your code cooperates with real infrastructure: an actual database, an HTTP client hitting a local server, a message queue. They're slower and catch wiring problems a unit test can't see. End-to-end tests drive the whole system through a user-facing path and are slowest of all.
The practical rule: a unit test should fail for exactly one reason and tell you which behavior broke. If a failing test's message leaves you guessing whether the bug is in your logic, your SQL, or your network config, the test is doing integration work. That's fine—it just belongs in a different suite with different expectations.
One caveat before the steps: there's no universal definition of "unit." In some communities, any test that runs without manual intervention counts as a unit test even if it touches a database, as long as it's fast enough. The design principles below still apply; you'd just relax the isolation requirement deliberately rather than by accident. Know which definition your team uses and write it down.
Start With the Behavior, Not the Function
The most common design mistake is writing tests that mirror implementation. You write calculateDiscount(), then write a test that calls calculateDiscount() with three inputs and checks three outputs—chosen because they're the ones you happened to think of, not because they represent anything meaningful.
Flip the order. Before writing or changing code, describe the behavior in a sentence: "A cart with a subtotal of $100 and a 10% coupon costs $90." That sentence becomes a test. The sentence form matters because it forces you to name the input, the action, and the expected outcome—exactly the three parts of a test.
This habit pays off in a specific way: behavior survives refactoring, but implementation doesn't. If you later split calculateDiscount() into two helpers or switch from one rounding strategy to another, a behavior-based test still describes what should happen and still passes if the outcome holds. A test that checks "calls applyPercentage() exactly once" fails the moment you refactor, even though nothing broke. That's a false alarm, and false alarms are how suites get disabled.
There's a balance to strike. Behavior tests can miss edge cases that live deep in a helper, so when you find a bug in a helper, test the helper directly too. But start at the behavior level for each unit's public surface, then go deeper only where the public tests don't reach. A rough guide: if a helper is pure and has tricky logic—parsing, rounding, sorting—give it its own focused tests. If it's a trivial one-liner, its behavior is covered by the caller's test.
Get the Structure Right: Arrange, Act, Assert
Almost every good unit test follows the same three-part shape. Arrange: set up the objects and inputs. Act: call the unit once. Assert: check the result.
Three design rules fall out of this shape.
One act per test. If you call the unit multiple times in one test, a failure doesn't tell you which call went wrong. Split it. The narrow exception is a loop over a table of cases—more on that below—where each iteration is logically a separate test.
One logical assertion per test. This doesn't mean one assert statement; it means one idea being verified. A test that checks the total and the discount amount and the tax is three tests wearing a trench coat. When it fails, you'll read the stack trace to find out which of those three things broke. Split them, name them clearly, and a failing test name tells you the story.
Tests don't share mutable state. Arrange builds everything fresh in each test. Shared setup that mutates between tests creates order-dependent failures, where a test passes alone but fails in the suite—or worse, passes in the suite and fails in CI because the order changed. If setup is genuinely expensive to repeat, extract a builder helper that each test calls; the helper returns fresh objects, so state stays isolated.
The name is part of the design. test_total_1 is useless. total_after_percent_coupon_rounds_to_cents tells you what broke before you open the file. A widely used convention is methodName_condition_expectedOutcome, but any consistent scheme that names condition and outcome works. Follow the house style—if the codebase uses a different pattern, match it rather than introducing a second dialect.
Choose Inputs That Find Bugs
The biggest quality difference between a beginner's suite and an experienced engineer's suite isn't tooling—it's case selection. A test with x = 5 proves almost nothing. The value is invested in the cases that sit at boundaries, where code usually breaks.
Boundaries and off-by-one errors. If a function accepts values 0 through 100, test 0, 100, and the values just outside—−1 and 101—to see what happens. If a loop runs "up to but not including n," test n−1 and n. Boundary bugs are the single most common category in arithmetic and indexing code.
Empty, null, and single-element inputs. Empty list, single-element list, list with one duplicate. These catch assumptions like "there's always a first element" that hold in your happy-path test and fall apart in production.
Equivalence classes. Inputs that should behave the same way can share one representative. If salaries under $50,000 get 10% and those at or above get 20%, you don't need to test every salary—test one below the line, one at the line, and one above. The class boundary, not the interior, is where bugs hide.
Invalid and error cases. What happens when the input is out of range, malformed, or a wrong type? A function that's supposed to throw an error should be tested for throwing it. Error handling that's never tested is error handling that's never exercised.
Interesting combinations. Most bugs live at intersections: a boundary value and an empty list, a discounted item and a tax exception. You can't test every pair, but you can test the pairs your requirements call out.
A table-driven test—one test iterating over a list of (input, expected) cases—is an efficient way to cover many cases with one readable block. Keep each row's expectation spelled out; don't compute the expected value with the same logic you're testing, or the test will pass no matter what the code does.
Worked example: a function that returns the middle element of an array. Happy path: [1, 2, 3] returns 2. Boundary: returns 1. Even length—does it return the lower or upper middle? Test whichever you chose, because that's a spec decision someone will hit. Empty array—does it throw, or return a sentinel? Test the documented behavior. Two tests would have found the empty-array crash; one test would have missed it.
Handle Dependencies Without Rewriting the World
Real units have dependencies: a clock, a random number generator, a payment gateway, a file system. Left uncontrolled, each one makes tests slow, flaky, or both. There are three ways to handle them, and the right choice depends on what you're testing.
Parameterize the dependency. The cleanest fix. Pass the clock in as an argument (def init(self, clock=datetime.utcnow)) instead of reading it inside the function. The test passes a fixed time; production passes the real one. Same for random seeds, IDs, and config. This keeps the code honest and the tests simple, and it's usually a bigger design improvement than any test tool.
Use a test double. When you can't or don't want to inject—say, a third-party API client—replace it with a test double, a stand-in object. Doubles come in flavors. A stub returns canned data: get_exchange_rate("USD", "EUR") returns 0.92 without calling the network. A spy records how it was called so you can check later. A mock combines both and is what most libraries provide. Use the smallest double that does the job; magic mock objects that respond to everything let a test pass even when the real dependency would fail.
Fake the infrastructure. For a database, an in-memory implementation (SQLite in memory, a fake repository class) often beats mocking the ORM method by method. Fakes behave like the real thing for the cases you need, and they don't break when the ORM's internals change.
What not to do: mock everything. A test that mocks five collaborators and then asserts on the order of calls is testing your implementation structure, not your behavior. When that test fails, the fix is usually to update the test, not the code—which means the suite is now just an extra tax on every refactor. The rule of thumb: mock what crosses a boundary you don't control (network, clock, filesystem, third-party library) and let everything you own run for real. If a "unit" needs six mocks to test, the unit is probably too big; that's a design signal, not a testing problem.
Make Tests Deterministic
A test that passes sometimes and fails sometimes is worse than no test: it trains everyone to re-run CI and ignore red. Flakiness has a short list of usual causes, and all of them are fixable by design.
Time. Assertions like "timestamp is within 1 second of now" fail at midnight, during leap seconds, or on slow CI. Inject a fixed clock and assert on the exact value.
Randomness. Generate a random ID and assert it matches a pattern—fine. Assert it equals a specific UUID—broken. Pass a seeded random generator when output must be predictable.
Order. Iterating a set or dictionary and asserting on the first item assumes an ordering that isn't guaranteed across languages and versions. Sort before asserting, or assert on the whole collection.
Network and file system. These are slow and failure-prone. If a unit test needs them, it's not a unit test; move it to the integration suite. If it needs them because the code reads a config file at import time, inject the config.
Shared state. Two tests touching the same global variable or database row will pass or fail based on order. Isolate per test.
Run the full suite several times in a row, and in a different order if your runner supports it, before trusting it. A test that fails only when it runs second has a state leak, and you'll want to find it before CI does.
How Many Tests, and What to Cover
Coverage percentage is a starting point at best. It tells you what code appears in a test, not whether the test checks anything. A suite at 95% coverage can still miss every boundary if the tests all use x = 5 on the happy path.
Cover the behaviors that carry risk. For each public function, ask: what are the documented inputs and outputs? What invalid input should it reject? What boundary values matter? What error paths exist? Write one test per answer, and you'll have a focused suite that catches the bugs that matter. For a helper with tangled logic and two callers, test it directly; for a plain getter, a single test is enough.
There's no magic number. Small projects do fine with a few dozen tests; large systems run into the thousands. The signal you want is a suite fast enough to run on every change—under a minute locally for most codebases—and failing tests whose names point straight at the broken behavior. When a test fails, the next step should be obvious: read the name, look at the assertion, and know which line broke. If you can't tell from the failure message, rewrite the test before fixing the code.
Track coverage as a trend, not a target. Watch it to see which modules are untested rather than chasing a number. A team that gates on 80% coverage will write tests that call functions without asserting much; a team that tracks coverage and reviews the tests will write the ones that catch bugs.
Write the Failing Check First
The workflow many teams find most effective starts with a failing test. Write the test, run it, and watch it fail for the expected reason. Then write enough code to pass, then clean up.
That's the test-first loop, and it has a design benefit beyond discipline: it proves the test can fail. A test you've never seen fail might be checking nothing—an assertion that's always true, a code path that's never reached, a typo that makes assert result always pass. Seeing red once confirms the test is wired to the code.
In practice the loop looks like: pick the next small behavior ("empty input returns zero"), write a test that calls the unit and asserts zero, run it and confirm it fails, write the smallest change that makes it pass, run the suite. Repeat with the next behavior. It's less a religion than a checkpoint—most people write some tests after the code, and that's fine, as long as every new test is run once and seen failing before it goes into the suite.
Two honest failure modes. First, test-first on exploratory code can feel like dragging an anchor; sketch first if you're still discovering the design, then add tests once the shape settles. Second, if your test fails for a reason you didn't predict—wrong import, typo in the expectation—fix the test, confirm it fails for the right reason, then make it pass. Don't let an unexpected red teach you the wrong thing.
Keep the Suite Healthy as It Grows
A suite that was fast and trusted at 200 tests can become slow and ignored at 2,000. Keep it healthy with a few maintenance habits.
Measure speed. Know how long the suite takes. If a single test takes more than ~100 ms, find out why—it's usually hitting the network or starting a server it shouldn't. Fast tests get run; slow suites get skipped.
Review test quality in code review. Same bar as production code: clear names, one behavior per test, no dead assertions, no commented-out tests. A commented-out test is a decision nobody recorded; delete it or fix it.
Delete tests that no longer test anything. When a function is deleted, its tests go too. When a behavior changes, update the test rather than deleting it—unless the behavior is genuinely gone. A test that passes for the wrong reason (e.g., a mock that returns nothing and the assertion checks for nothing) is worse than a missing test.
Watch for fragile tests. If you update assertions after most refactors, the tests are coupled to implementation. Rewrite them at the behavior level. A healthy suite changes only when behavior changes.
Group by unit, not by state. Most runners support test classes or files per module. Keep them independent and runnable in isolation, since that's how you'll run them while debugging. A well-organized suite lets you run one file and get a useful signal in under a second.
A Short Walkthrough With a Success Check
Say you're adding a function that splits a total price into equal installments, each rounded to cents, with the last installment absorbing the rounding remainder.
Prerequisite: pick a test framework for your language (pytest for Python, JUnit for Java, Jest or Vitest for JavaScript, Go's built-in testing) and a directory the runner picks up.
1: Name the behavior: "splitting 100.00 into 3 installments yields 33.33, 33.33, and 33.34." 2: Write the test with that exact expectation. Arrange the inputs, call the function once, assert on the full list—not just the sum, because a wrong distribution that still sums correctly is exactly the bug you're guarding against. 3: Run it. It fails with a "function not defined" error. That's the expected red. 4: Write the function: divide, round each share down to cents, and give the remainder to the last installment. 5: Run again. Green.
Success check: add cases for one installment (the whole amount), zero installments (defined error or empty list), and an uneven amount like 10.00 into 3 (3.33, 3.33, 3.34). Run each and confirm the failure messages are readable before you fix anything. If a case surprises you, you've found a spec hole—decide the intended behavior and encode it in the test.
Stop condition: if a unit only works by talking to a live service, a real database, or a fixed wall-clock time you can't inject, don't force a unit test around it. Wrap the dependency behind an interface, test what you can in isolation, and move the rest to an integration suite with a professional-owned environment. When test failures only reproduce on CI and correlate with time or concurrency, bring in whoever owns the build infrastructure; the fix is architectural, not a better assertion.
FAQ
Should I use mocks or fakes for a database? Prefer a fake—an in-memory implementation of the same interface. It exercises real code paths and survives internal refactors. Use mocks when the dependency is a third-party service you can't run locally, and keep the mock surface as small as possible.
Do I need 100% coverage? No. Cover behaviors and edge cases; the last few percent of lines are often error paths that are hard to trigger and rarely change. Treat coverage as a map of untested risk, not a score.
How do I test code that reads the clock or generates random IDs? Pass them in as parameters with a sensible production default. Tests supply a fixed clock or a seeded generator, then assert on exact values. This also makes the code easier to reason about outside tests.
When is a unit test the wrong tool? When the thing you're verifying is how components connect—a query against a real schema, a full request through a framework, a migration. Those belong in integration or end-to-end tests, where the cost of setup is justified by what they catch.