Unit Testing: What It Is, Examples and Best Practices
Unit testing is checking the smallest pieces of a program, usually one function or class at a time, with automated tests that run in milliseconds without a database or network and report pass or fail on their own. A unit test is one of those checks.
When a coding agent writes the code and its tests, Zest shows which sessions and models each pull request took, and what they cost. Start freeGet started
The unit testing best practices that matter most: test behavior through the public interface, give each test one behavior and a name that says what it is, keep tests fast and deterministic, prefer real objects and fakes to mocks, write a failing test for every bug before you fix it, and run the suite on every pull request. Below are a definition, the same test in Python, JavaScript and Java, what to test, and what changes when a coding agent writes the code.
What is a unit test?
A unit test is a short piece of code that calls one unit of your program with known inputs and checks the result. Martin Fowler names three things most definitions share: unit tests are low-level, “focusing on a small part of the software system”; programmers write them “themselves using their regular tools”; and they are “expected to be significantly faster than other kinds of tests” (Martin Fowler).
What counts as a unit is up to you. Fowler: “the team decides what makes sense to be a unit”. Google’s engineering book uses the term for “tests of relatively narrow scope, such as of a single class or method” (Software Engineering at Google, chapter 12). Teams also differ on whether a unit test may use the unit’s real collaborators. Fowler uses Jay Fields’ names for the two styles: solitary tests replace every collaborator with a test double, sociable tests use the real ones. Both are unit tests.
Microsoft’s .NET guide lists five traits of a good unit test, and none of them is specific to .NET (Microsoft Learn):
- Fast: milliseconds per test, because mature projects have thousands.
- Isolated: no dependency on “outside factors, such as a file system or database”.
- Repeatable: the same result on every run if nothing changed.
- Self-checking: the test decides pass or fail with no person looking.
- Timely: it doesn’t take much longer to write than the code it tests. If it does, the design is hard to test.
What does a unit test look like? Examples in Python, JavaScript and Java
Here is one function in three languages. It splits a bill in cents among some number of people, gives the leftover cents to the first people, and refuses to split among zero. The tests cover what most units need: a normal case, an edge case, a rule that must always hold, and an error. We ran every sample on this page, and each passes as written.
Python unit testing with pytest
# bill.py
def split_bill(total_cents, people):
if people < 1:
raise ValueError("people must be at least 1")
share, remainder = divmod(total_cents, people)
return [share + 1 if i < remainder else share for i in range(people)]
# test_bill.py
import pytest
from bill import split_bill
def test_splits_evenly_when_the_total_divides():
assert split_bill(900, 3) == [300, 300, 300]
def test_gives_leftover_cents_to_the_first_people():
assert split_bill(1000, 3) == [334, 333, 333]
@pytest.mark.parametrize("total, people", [(1, 2), (999, 7), (0, 4)])
def test_shares_always_add_up_to_the_total(total, people):
assert sum(split_bill(total, people)) == total
def test_rejects_zero_people():
with pytest.raises(ValueError):
split_bill(1000, 0)
Run python -m pytest. pytest collects files named test_*.py or *_test.py and functions that start with test_, and checks plain assert statements (pytest docs). @pytest.mark.parametrize runs one test function with several sets of arguments (pytest docs), and pytest.raises passes only when the code raises that exception.
JavaScript unit testing with Vitest
// bill.js
export function splitBill(totalCents, people) {
if (!Number.isInteger(people) || people < 1) {
throw new RangeError("people must be a whole number of at least 1");
}
const share = Math.floor(totalCents / people);
const remainder = totalCents % people;
return Array.from({ length: people }, (_, i) => (i < remainder ? share + 1 : share));
}
// bill.test.js
import { describe, expect, it } from "vitest";
import { splitBill } from "./bill.js";
describe("splitBill", () => {
it("gives leftover cents to the first people", () => {
expect(splitBill(1000, 3)).toEqual([334, 333, 333]);
});
it.each([
[1, 2],
[999, 7],
[0, 4],
])("splits %i cents among %i people without losing a cent", (total, people) => {
const shares = splitBill(total, people);
expect(shares.reduce((sum, share) => sum + share, 0)).toBe(total);
});
it("rejects zero people", () => {
expect(() => splitBill(1000, 0)).toThrow(RangeError);
});
});
Run npx vitest run. Vitest runs files with .test. or .spec. in the name (Vitest docs). Its docs say it is compatible with most of Jest’s API, so in most projects it “should be a drop-in replacement for Jest” (Vitest); toEqual, toBe and toThrow are Jest matchers too.
Java unit testing with JUnit
// src/main/java/bill/Bill.java
package bill;
public final class Bill {
private Bill() {}
public static long[] split(long totalCents, int people) {
if (people < 1) {
throw new IllegalArgumentException("people must be at least 1");
}
long share = totalCents / people;
long remainder = totalCents % people;
long[] shares = new long[people];
for (int i = 0; i < people; i++) {
shares[i] = i < remainder ? share + 1 : share;
}
return shares;
}
}
// src/test/java/bill/BillTest.java
package bill;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class BillTest {
@Test
void givesLeftoverCentsToTheFirstPeople() {
assertArrayEquals(new long[] {334, 333, 333}, Bill.split(1000, 3));
}
@ParameterizedTest
@CsvSource({"1, 2", "999, 7", "0, 4"})
void sharesAddUpToTheTotal(long total, int people) {
assertEquals(total, Arrays.stream(Bill.split(total, people)).sum());
}
@Test
void rejectsZeroPeople() {
assertThrows(IllegalArgumentException.class, () -> Bill.split(1000, 0));
}
}
The test uses JUnit Jupiter, the API that JUnit 5 and JUnit 6 share. “All JUnit Jupiter assertions are static methods in the org.junit.jupiter.api.Assertions class” (JUnit User Guide), and @ParameterizedTest runs one method “multiple times with different arguments” (JUnit User Guide).
To run it, add the org.junit.jupiter:junit-jupiter test dependency, which pulls in the API, parameterized tests and the engine (JUnit dependency metadata). Then run mvn test, which needs Maven Surefire 3.0.0 or later for JUnit 6, or gradle test with useJUnitPlatform() in the test block (JUnit build support). JUnit 6.0 came out on September 30, 2025 and needs Java 17 or later (release notes); on older Java, stay on JUnit 5. We ran this test unchanged on JUnit 6.1.3 and on JUnit 5.14.4.
For C#, the same ideas with xUnit, NUnit and MSTest are in unit testing in C#.
What should you unit test, and what not?
Unit test the logic your code owns, through the methods its callers use. For each unit that usually means:
- The normal case, with the simplest input that shows the behavior.
- Boundaries: zero, one, empty, the largest value, the last day of the month.
- Error paths: bad input, and a dependency that fails or times out.
- Every bug you fix, as a test that fails before the fix and passes after, so the bug can’t come back unnoticed. AI code debugging walks through this with a coding agent.
Leave these out:
- Private methods on their own. Microsoft’s guide: “In most cases, you don’t need to test a private method”, because it’s an implementation detail. Test the public method that calls it.
- Code you don’t own, such as the framework or a library. Test how your code uses it.
- Anything that needs a real database, network or file system. Microsoft says those dependencies “make the tests slow and brittle and should be reserved for integration tests”.
Unit testing best practices
The first nine come from Google’s, Microsoft’s and Martin Fowler’s published guidance; the tenth is where to run them.
1. Test behavior through the public API
Google’s book says to write tests “that invoke the system being tested in the same way its users would”, and “rather than writing a test for each method, write a test for each behavior”. Such a test survives a refactor, because a refactor doesn’t change what callers see.
2. One behavior per test, named after it
When a test checks one thing, a red result tells you what broke. Microsoft’s test names have three parts, the method, the scenario and the expected behavior, as in Add_SingleNumber_ReturnsSameNumber. In pytest a sentence works too: test_gives_leftover_cents_to_the_first_people.
3. Arrange, Act, Assert
Set up the inputs, call the code once, check the result, with a blank line between the three parts. Microsoft’s guide says the pattern separates “what is being tested from the Arrange and Assert tasks”. The mock example below uses that layout.
4. Keep tests fast, isolated and order-free
Google’s “small” tests may not use the network, a database, the file system, extra threads or sleep statements, and must finish within 60 seconds. Every Google test must also run “in any order”, so no test relies on data another one left behind (Google Testing Blog, 2010). Speed keeps people running the suite: Fowler likes Kent Beck’s rule of thumb that “the commit suite should run in no more than ten minutes.”
5. Control time and randomness
Code that reads the clock can pass on Monday and fail on Tuesday. Microsoft’s example is a Tuesday-only discount whose two tests can never pass on the same day. Pass the clock, the date or the random seed in as an argument and let the test choose it; the reminder example below takes today that way.
6. Keep logic out of tests
Google: “in test code, stick to straight-line code over clever logic.” Microsoft warns against if, while, for and switch in tests: “The last place you want to find a bug is within your test suite.” For many inputs, use a parameterized test (@pytest.mark.parametrize, it.each, @ParameterizedTest).
7. Make a failure say what went wrong
A failure message should “clearly express the desired outcome, the actual outcome, and any relevant parameters”, Google’s book says. Assert on values (assertEquals, toEqual, assert a == b) rather than on a boolean, so the runner prints both sides. When we broke split_bill on purpose, pytest printed the failing parameters and assert 0 == 1.
8. Prefer real objects and fakes to mocks
Use the real dependency when it’s fast and deterministic, a fake when it isn’t, and a mock last. The next section gives Google’s reasons.
9. Use coverage as a map, not a target
Coverage shows which lines no test runs, not whether the tests check anything: it “just guarantees that they have been executed by a test” (Google Testing Blog, 2020). Google calls 60% “acceptable”, 75% “commendable” and 90% “exemplary”. To see whether tests really assert, the same post points to mutation testing, which breaks the code on purpose and checks that some test fails.
10. Run the suite on every change, and in CI
Run the tests while you work, then have CI run them on every pull request and block the merge while they’re red (CI/CD platforms compares where to run them). Failing tests then never reach a reviewer, the third of our code review best practices.
Mocks, stubs and fakes: which should you use?
A test double stands in for a real dependency in a test. Gerard Meszaros named five kinds, and Martin Fowler’s Mocks Aren’t Stubs gives his definitions:
| Test double | What it does | Example |
|---|---|---|
| Dummy | “Passed around but never actually used” | An argument the code path never touches |
| Stub | Gives “canned answers to calls made during the test” | A price service that always returns 100 |
| Spy | A stub that also records how it was called | A stub that counts calls |
| Mock | Pre-programmed with expectations about the calls it should get | A mailer that must be called once with these arguments |
| Fake | A working implementation that “usually take[s] some shortcut” | An in-memory database |
The line that matters: “only mocks insist upon behavior verification. The other doubles can, and usually do, use state verification.” A mock checks how your code called it, while the other doubles let you check what came out. Tools blur the words: in Microsoft’s .NET guide “fake” is the generic term for both stubs and mocks.
Google’s order of preference is the real implementation, then a fake, then a mock. “A mock reduces fidelity, since it doesn’t execute any of the actual implementation of a dependency”, though mocks are useful for a path that’s hard to trigger, such as a timeout (Google Testing Blog, 2024). Google’s book is blunter: “One lesson we learned the hard way is the danger of overusing mocking frameworks”; such tests “required constant effort to maintain while rarely finding bugs” (chapter 13).
Here is one rule tested both ways: email a reminder for every unpaid invoice past its due date.
# reminders.py
from dataclasses import dataclass
from datetime import date
@dataclass
class Invoice:
id: int
email: str
due: date
paid: bool
def send_overdue_reminders(invoices, today, mailer):
for invoice in invoices:
if invoice.due < today and not invoice.paid:
mailer.send(invoice.email, f"Invoice {invoice.id} is overdue")
# test_reminders.py
from datetime import date
from unittest.mock import Mock
from reminders import Invoice, send_overdue_reminders
TODAY = date(2026, 11, 12)
INVOICES = [
Invoice(id=1, email="a@example.com", due=date(2026, 11, 1), paid=False),
Invoice(id=2, email="b@example.com", due=date(2026, 11, 1), paid=True),
Invoice(id=3, email="c@example.com", due=date(2026, 12, 1), paid=False),
]
class FakeMailer:
"""Keeps sent messages in a list instead of sending them."""
def __init__(self):
self.sent = []
def send(self, to, body):
self.sent.append((to, body))
def test_reminds_only_unpaid_overdue_invoices():
mailer = FakeMailer()
send_overdue_reminders(INVOICES, today=TODAY, mailer=mailer)
assert mailer.sent == [("a@example.com", "Invoice 1 is overdue")]
def test_reminds_only_unpaid_overdue_invoices_with_a_mock():
mailer = Mock()
send_overdue_reminders(INVOICES, today=TODAY, mailer=mailer)
mailer.send.assert_called_once_with("a@example.com", "Invoice 1 is overdue")
Both tests pass, and both failed when we made the code remind paid invoices too. The fake checks state, the messages that would have gone out; the mock checks the call. Python’s unittest.mock is in the standard library. In Java the usual choice is Mockito (mock(), when().thenReturn(), verify()), and in JavaScript it’s vi.fn() in Vitest or jest.fn() in Jest.
Unit tests vs integration tests vs end-to-end tests
Google sorts tests by what they’re allowed to touch. In its 2010 scheme, “A Small test equates neatly to a unit test, a Large test to an end-to-end or system test”, and a Medium test to what is “often called an integration test” (Google Testing Blog).
| Unit test | Integration test | End-to-end test | |
|---|---|---|---|
| What it checks | One function or class | That two parts work together, such as your code and a database | The whole application, the way a user drives it |
| Google’s size | Small | Medium | Large |
| Network | No | Localhost only | Yes |
| Database and file system | No | Yes | Yes |
| Time limit at Google | 60 seconds | 300 seconds | 900 seconds and more |
How many of each? Martin Fowler’s test pyramid, which he credits to Mike Cohn’s 2009 book Succeeding with Agile, says to have “many more low-level UnitTests than high level BroadStackTests running through a GUI”, because tests through the UI are “brittle, expensive to write, and time consuming to run”. Google’s book suggests “a mix of about 80% unit tests and 20% broader-scoped tests”.
Unit testing frameworks by language
| Language | Framework | Mocks | Run tests with |
|---|---|---|---|
| Python | pytest; unittest in the standard library | unittest.mock, in the standard library since Python 3.3 | python -m pytest |
| JavaScript and TypeScript | Vitest, Jest, or node:test, built into Node.js | vi.fn(), jest.fn() |
npx vitest run, npx jest, node --test |
| Java | JUnit: 6 on Java 17 and later, 5 before that | Mockito | mvn test, gradle test |
| C# | xUnit.net, NUnit, MSTest (our guide) | Moq, NSubstitute | dotnet test |
| Go | The testing package; test files end in _test.go |
None built in | go test |
| Rust | Built in: functions marked #[test] |
None built in | cargo test |
Versions on November 12, 2026: pytest 9.2.0, Vitest 5.1.0 (it needs Node.js 22.12 or later), Jest 30.5, JUnit 6.1.3, Mockito 5.24. Python’s unittest “was originally inspired by JUnit”, and node:test has been stable since Node.js 20.
How do you unit test code a coding agent writes?
Give the agent tests it can run, make running them automatic, and review the tests it writes as closely as the code.
Give the agent a check to run
Anthropic’s Claude Code docs explain why: “Claude stops when the work looks done. If it has nothing to run that tells it whether the work actually is done, ‘looks done’ is all it has to go on.” They suggest putting the test command in CLAUDE.md, asking for a bug fix as “write a failing test that reproduces it, then fix it”, and asking for evidence, since “‘All tests pass’ on its own tells you very little” (Claude Code best practices).
Run the tests with a Stop hook
To make it automatic, use a Claude Code hook. A Stop hook runs each time Claude finishes responding; if its command exits with code 2, Claude gets what the command wrote to stderr and keeps working. The docs’ example runs a type check; this one runs the unit tests:
{
"hooks": {
"Stop": [
{
"hooks": [
{ "type": "command", "command": "npx vitest run 1>&2 || exit 2" }
]
}
]
}
}
After eight blocked stops in a row with no tool call between them, Claude Code lets the turn end anyway. The hook runs on every turn, so give it the fast unit suite, not the end-to-end tests.
Review the tests it writes
In our own two repositories, 86% of the 866 agent-written pull requests we studied (merged August 12 to October 4, 2026) touched a test file, against 61% of the pull requests merged in the same weeks without the agent’s summary block. Local testing took 29% of the session minutes the agents reported (what 866 agent-written pull requests show). But “touched” can’t tell a new test from an edited one. When you review an agent’s tests, look for a test weakened or deleted in the same diff as the fix, mocks so thorough that no real code runs, and assertions that copy today’s output, bugs included. Committing the tests before the implementation, as in red-green-refactor, makes the first of those easy to spot.
Zest is ours, and it doesn’t run, write or measure your tests: it collects no coverage and no code diffs. It records each engineer’s coding-agent sessions, tool calls included, and links each one to the GitHub pull request it led to, so you can see which sessions and models a change took and what they cost. Keep your test runner and CI for the tests themselves.
Frequently asked questions
What is the difference between unit testing and integration testing?
A unit test checks one function or class on its own, with no network, database or file system, so it runs in milliseconds and a failure points at that unit. An integration test checks that parts work together, such as your code and a real database. In Google’s terms, unit tests are “small” and must “run in a single process” (Google Testing Blog, 2024); integration tests are “medium”.
What is a good code coverage percentage for unit tests?
There’s no single right number. Google’s guidelines call 60% “acceptable”, 75% “commendable” and 90% “exemplary”, with per-commit goals of 99% “reasonable”. The same post warns that pushing toward 100% “leads to a false sense of security”, because coverage shows what ran, not what was checked.
Should you unit test private methods?
No. Test them through the public methods that call them. Microsoft’s guide says private methods “are an implementation detail and never exist in isolation”. If one seems to need tests of its own, it may belong in a separate class or module with a public interface.
Is unit testing the same as test-driven development?
No. Test-driven development is a way of working: write a failing test, make it pass, clean up, repeat. It produces unit tests, but unit tests written after the code are still unit tests, just not TDD. See red, green, refactor for the loop.
Which unit testing framework should I use for Java?
JUnit, with Mockito for mocks. JUnit 6 needs Java 17 or later; on older Java, use JUnit 5. Both use the JUnit Jupiter API, so the test above runs unchanged on either.
Zest is AI coding analytics for engineering teams: it shows which coding agents, models and skills each engineer uses, what they cost, and which sessions end in merged pull requests. See how Zest works.