Testing Fundamentals
Unit, integration and end-to-end tests, the test pyramid, arrange-act-assert, test doubles, TDD and what makes a test good.
What is it?
A test is code that runs your code and checks the result automatically. Tests catch regressions, document how code is meant to behave, and let you change code with confidence.
Tests come in three broad sizes:
- Unit tests check one small piece (a function or class) in isolation. They're fast and pinpoint failures precisely. - Integration tests check that several pieces work together: your code with a real database, or two modules through their real interfaces. - End-to-end (E2E) tests drive the whole system like a user would, through the UI or public API. They give the most confidence per test but are slow and more brittle.
The test pyramid suggests many unit tests, fewer integration tests and a handful of E2E tests.
Most tests follow Arrange-Act-Assert: set up the inputs, run the code, check the outcome. When the code under test depends on something slow or unpredictable (network, clock, payment provider), you substitute a test double: a stub, mock, fake or spy.
Test-driven development (TDD) reverses the usual order: write a failing test first, write just enough code to pass it, then refactor.
Explain like I'm 10
Unit tests are checking each ingredient before cooking; integration tests are tasting the sauce once things are combined; an end-to-end test is serving the full meal to a guest. You want to catch a bad egg at the ingredient stage, not when the guest is eating.
Examples
A unit test with Arrange-Act-Assert (Python, pytest)
def apply_discount(price: float, percent: float) -> float:
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)
def test_apply_discount_reduces_price():
# Arrange
price, percent = 80.0, 25
# Act
result = apply_discount(price, percent)
# Assert
assert result == 60.0
def test_apply_discount_rejects_invalid_percent():
import pytest
with pytest.raises(ValueError):
apply_discount(80.0, 150)Replacing a dependency with a fake (TypeScript, Vitest)
import { describe, it, expect, vi } from "vitest";
interface Clock { now(): Date }
function greeting(clock: Clock): string {
return clock.now().getHours() < 12 ? "Good morning" : "Good afternoon";
}
describe("greeting", () => {
it("says good morning before noon", () => {
const fakeClock: Clock = { now: () => new Date("2024-01-01T09:00:00") };
expect(greeting(fakeClock)).toBe("Good morning");
});
it("asks the clock exactly once", () => {
const mockClock = { now: vi.fn(() => new Date("2024-01-01T15:00:00")) };
greeting(mockClock);
expect(mockClock.now).toHaveBeenCalledTimes(1); // verifies the interaction
});
});Passing the clock in (dependency injection) makes time controllable. The first test checks the result; the second uses a mock to verify how the dependency was called. Prefer result checks; interaction checks couple tests to implementation.
How it works
A test runner (pytest, Vitest, Jest, JUnit, go test, cargo test) finds test functions, runs each in isolation, and reports which assertions failed. Good runners show a diff between expected and actual values.
Test doubles stand in for real dependencies:
- Dummy: passed to fill a parameter, never used. - Stub: returns canned answers ("the API returns this user"). - Fake: a working but simplified implementation (an in-memory database). - Spy: records how it was called so you can inspect it afterwards. - Mock: pre-programmed with expectations about calls, and fails the test if they aren't met.
TDD runs in short cycles called red, green, refactor: write a test that fails (red), make it pass with the simplest code (green), then clean up the code with the test as a safety net.
Coverage tools report which lines ran during tests. High coverage shows what wasn't tested; it doesn't prove that what ran was checked well.
/\
/E2E\ few: slow, broad, most realistic
/------\
/integra-\ some: real components together
/ tion \
/------------\
/ unit \ many: fast, focused, isolated
/----------------\Why does it exist?
Manually re-checking everything after each change is slow and unreliable, and bugs found late (in production) cost far more to fix than bugs found minutes after writing the code. Automated tests make checking cheap enough to do on every change, and they allow refactoring without fear because a broken behaviour shows up immediately.
When to use it
Write unit tests for logic with branches, calculations, parsing and edge cases. Write integration tests where your code meets something external (database queries, HTTP clients, file formats). Keep a few E2E tests for critical user journeys (sign-up, checkout). For every bug you fix, add a test that fails without the fix. TDD works best when requirements are clear and the logic is non-trivial.
When not to use it
Don't unit-test trivial code (plain getters, framework configuration) or private helpers directly: test them through the public behaviour that uses them. Don't mock everything; tests full of mocks pass while the real integration is broken. Don't chase 100% coverage as a goal in itself. For throwaway prototypes and spikes, heavy test suites may not pay off.
Common mistakes
Testing implementation details (private methods, exact call sequences) so tests break on every refactor even when behaviour is unchanged.
Over-mocking, so tests only verify that the mocks were configured, not that the system works.
Tests that depend on each other or on shared state, so they pass alone but fail together (or in a different order).
Flaky tests that depend on real time, randomness or network, which teach the team to ignore failures.
Asserting nothing meaningful, e.g. only checking that no exception was thrown or that a result is 'truthy'.
Practice exercises
- Easy:
Write three unit tests for a
isLeapYear(year)function: a normal leap year, a century that is not a leap year (1900), and a century that is (2000). - Medium:
Write a
WeatherServicethat fetches a temperature through an injected HTTP client, and test it with a stub client covering success, a network error and malformed data. - Hard:
Use TDD to build a string calculator
add("1,2\n3")that supports commas and newlines, rejects negatives with a message listing them, and ignores numbers over 1000. Commit after each red-green-refactor cycle.
Interview questions
What is the difference between unit, integration and end-to-end tests?
Unit tests check a single unit (function or class) in isolation. Integration tests check several components working together, often with real infrastructure like a database. End-to-end tests exercise the whole system through its real interface, as a user would.
What is the test pyramid?
A guideline to have many fast unit tests at the base, fewer integration tests in the middle and a small number of slow end-to-end tests at the top, balancing confidence against speed and maintenance cost.
What is Arrange-Act-Assert?
A structure for tests: Arrange sets up inputs and dependencies, Act invokes the behaviour under test, Assert verifies the outcome. It keeps tests readable and focused on one behaviour.
What is the difference between a stub, a mock and a fake?
A stub returns canned data to drive the code under test. A mock is configured with expectations about how it should be called and verifies them. A fake is a lightweight working implementation, such as an in-memory repository.
What is TDD?
Test-driven development: write a failing test first, write the minimum code to make it pass, then refactor while keeping tests green. It drives design from the caller's perspective and ensures every behaviour has a test.
What makes a good unit test?
It's fast, isolated, deterministic and readable; tests one behaviour through the public interface; has a descriptive name; and fails for exactly one reason with a clear message. The FIRST acronym: Fast, Isolated, Repeatable, Self-validating, Timely.
Does 100% code coverage mean the code is bug-free?
No. Coverage shows which lines executed, not whether the assertions were meaningful or whether all input combinations and edge cases were checked. It's useful for finding untested code, not for proving correctness.
What is a flaky test and how do you fix it?
A test that sometimes passes and sometimes fails without code changes, usually because of timing, shared state, randomness, test order or real network calls. Fix it by controlling those sources: inject clocks and random seeds, isolate state, and wait on conditions instead of fixed sleeps.
Why should you test behaviour rather than implementation?
Tests tied to internals break whenever you refactor, even when the behaviour is correct, which makes them a burden. Tests through the public interface stay valid across refactors and only fail when something users rely on changes.
Why write a test when fixing a bug?
A test that reproduces the bug proves the fix works (it fails before and passes after) and prevents the same bug from silently returning later: a regression test.