123DevOps··8 min read

Software testing: unit, integration, end-to-end, and the test pyramid

Learn what automated tests are for, the difference between unit, integration, and end-to-end tests, how to use the test pyramid, and how to run everything in CI without suffering from flaky tests.

Development

Imagine a mechanic who replaces your brake pads and hands the car back without a quick drive around the block. Maybe everything is fine, but you wouldn’t want to find out on the first steep hill. Software tests are that drive around the block: small programs that check, automatically and repeatably, whether your code does what it should.

In this guide, we start from zero: why test, what the types of tests are, what the famous test pyramid is, and how to get everything running in CI.

Why write tests?

An automated test is code that calls other code and checks the result. If the result is what you expected, the test passes; if not, it fails and tells you. The main benefits:

  • Confidence to change things: you can refactor (reorganize code without changing its behavior) knowing that if you break something, a test will catch it.
  • Bugs found early: a bug caught on your laptop costs minutes; the same bug in production can cost customers and a sleepless night.
  • Living documentation: a good test shows how a function is meant to be used, and it never goes stale, because if it does, it fails.
  • Frequent delivery: teams that integrate code several times a day, as in trunk-based development, rely on tests to keep the main branch from breaking.

The test pyramid

The test pyramid was popularized by Mike Cohn in his book Succeeding with Agile. The idea is simple: have many small, fast tests at the base, some mid-sized tests in the middle, and few large, slow tests at the top.

              /\
             /  \         End-to-end (E2E): few
            / E2E\        slow, expensive, more fragile
           /------\
          /        \      Integration: some
         /Integration\    test parts talking to each other
        /------------\
       /              \   Unit: many
      /      Unit      \  fast, cheap, stable
     /__________________\

Why this shape? The higher up the pyramid, the more parts of the system a test touches. That makes it more realistic, but also slower, more expensive to maintain, and more likely to fail for reasons that have nothing to do with your code (a slow network, a service that’s down). The inverse of the pyramid, with lots of E2E tests and almost no unit tests, is often called the “ice cream cone,” and it usually means a slow pipeline and little confidence.

Unit Integration End-to-end (E2E)
Scope A single function or class in isolation Two or more real parts (code + database, queue, API) The whole system, as the user sees it
Speed Milliseconds Seconds Seconds to minutes
Cost to write and maintain Low Medium High
Flakiness Rare Occasional More common
When it fails, it points to The exact line with the problem The conversation between components “Something” in the flow
Common tools pytest, JUnit, Jest, go test Testcontainers, Docker Compose Playwright, Cypress, Selenium

Unit tests in practice

A unit test checks the smallest useful piece of code, usually a function, with no database, network, or disk. Here’s a discount function in Python:

# shop/pricing.py
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)

And the tests with pytest, Python’s most popular testing framework:

# tests/test_pricing.py
import pytest

from shop.pricing import apply_discount


def test_applies_ten_percent():
    assert apply_discount(200.0, 10) == 180.0


def test_zero_discount_keeps_the_price():
    assert apply_discount(59.9, 0) == 59.9


def test_invalid_percent_raises_error():
    with pytest.raises(ValueError):
        apply_discount(100.0, 150)

Notice that we test the happy path, an edge case (zero discount), and an error case. To run them:

pip install pytest
pytest -q

Integration tests with a real database

An integration test checks whether two or more parts work together. The classic example: can your code actually save and read data in the database? Faking the database doesn’t answer that question, because the problem might be in the SQL itself.

Testcontainers is a library (available for Python, Java, Go, Node.js, and other languages) that starts a disposable Docker container during the test and destroys it at the end. That way, every run starts with a clean database, just like production:

# tests/test_orders_integration.py
import sqlalchemy
from testcontainers.postgres import PostgresContainer


def test_saves_and_reads_order():
    with PostgresContainer("postgres:16-alpine") as pg:
        engine = sqlalchemy.create_engine(pg.get_connection_url())
        with engine.begin() as conn:
            conn.execute(sqlalchemy.text(
                "CREATE TABLE orders (id SERIAL PRIMARY KEY, total NUMERIC(10, 2))"
            ))
            conn.execute(sqlalchemy.text("INSERT INTO orders (total) VALUES (99.90)"))
            total = conn.execute(sqlalchemy.text("SELECT total FROM orders")).scalar_one()
        assert float(total) == 99.90

To run it, you need Docker running and pip install "testcontainers[postgres]" sqlalchemy psycopg2-binary. If Docker is still new to you, see what is Docker.

End-to-end tests with Playwright

An end-to-end test (E2E) opens a real browser and acts like a user: it clicks, types, and checks what shows up on screen. Playwright is one of the most widely used tools for this:

// e2e/cart.spec.ts
import { test, expect } from '@playwright/test';

test('adds a product to the cart', async ({ page }) => {
  await page.goto('http://localhost:3000/');
  await page.getByRole('link', { name: 'Basic T-shirt' }).click();
  await page.getByRole('button', { name: 'Add to cart' }).click();
  await expect(page.getByTestId('cart-count')).toHaveText('1');
});

It waits for elements to appear automatically, which already removes a good share of flakiness. Even so, save E2E tests for the critical business flows: login, checkout, sign-up. Run them with npx playwright test.

Other kinds of tests worth knowing

  • Contract tests: check that an API’s consumer and its provider agree on the message format. Pact is the best-known tool, and it saves you from spinning up every microservice just to test one integration.
  • Smoke tests: a quick check right after a deploy (“does the home page load? does /health respond?”). The name comes from electronics: turn the device on and see if smoke comes out.
  • Load tests: measure how the system behaves under many simultaneous users. k6 lets you write these scenarios in JavaScript and run them with k6 run script.js.
  • Security tests: static code analysis, scanning dependencies for vulnerabilities, and tools like OWASP ZAP against the running application.
  • Resilience tests: inject failures on purpose to see whether the system recovers, the subject of chaos engineering.

Test doubles: mock, stub, and fake

Sometimes you want to test a function that calls something slow or unpredictable, like a payment API. That’s where test doubles come in, like the stunt doubles who replace actors in dangerous movie scenes:

  • Stub: returns a canned answer. “When asked for the exchange rate, answer 5.00.”
  • Mock: besides answering, it records how it was called so you can check later (“was the email function called once, with this recipient?”).
  • Fake: a simplified implementation that actually works, such as a repository that keeps data in an in-memory dictionary instead of the database.

Use doubles sparingly. If everything is faked, the test passes but proves nothing about whether the real parts work together.

Coverage: a good signal, a terrible target

Code coverage is the percentage of lines executed by your tests (in Python, pytest --cov=shop with the pytest-cov plugin). It’s useful for finding parts with no tests at all. But once it becomes a mandatory target, you start seeing tests that run the code without checking anything, just to push the number up. High coverage doesn’t guarantee good tests; very low coverage, however, is a clear warning sign.

Flaky tests and quarantine

A flaky test is one that sometimes passes and sometimes fails without any change to the code. The most common causes are dependence on the clock, execution order, fixed waits (sleep), and external services. The danger is cultural: the team gets used to clicking “re-run” and starts ignoring real failures.

The recommended practice is quarantine: move the flaky test to a separate group that doesn’t block merges, open a task with an owner and a deadline, fix it, and bring it back to the main suite. Automatic retries help buy time, but they aren’t the solution.

Tests in CI and parallelization

Tests only really protect you when they run automatically on every push and every pull request, in CI (continuous integration). An efficient order is to run unit tests first (they fail fast and cheap), then integration, and finally E2E. To speed things up, split the suite across processes or machines:

# pytest across several processes (pytest-xdist plugin)
pip install pytest-xdist
pytest -n auto

# Playwright split across 4 CI machines (this is part 1)
npx playwright test --shard=1/4

For more techniques, see how to cut a pipeline from 40 to 10 minutes. And remember: passing tests don’t replace a well-done code review; the two complement each other.

Checklist

  • Most of the suite is fast unit tests
  • Critical integrations (database, queue) tested against real dependencies via containers
  • E2E tests cover only the main business flows
  • Tests run automatically in CI on every pull request
  • Flaky tests go to quarantine with an owner and a deadline
  • Coverage tracked as a signal, not a target
  • Suite parallelized to keep feedback within a few minutes

A good test doesn’t prove your code is perfect; it makes sure you’ll find out, fast, when it stops being so.

Get updates on new posts and stay in the loop!