All articles
165 articles · updated weekly See our Tools
All articles
Comparisons

Unit test vs integration test: the difference in practice

The difference between unit and integration tests with API and database examples: what each one catches, what it costs, and when to use each in your project.

Unit test vs integration test: the difference in practice
COVER · Comparisons

The user repository was covered. Ninety-one percent coverage, all tests green, deploy out the door. Then the team noticed that sign-up was saving users without sending the confirmation email. The bug was in the integration between the user service and the email service — two individually perfect components that had never been tested together.

The difference in one sentence: a unit test verifies a single unit of code in isolation, with its dependencies replaced by test doubles; an integration test verifies that two or more real parts work together — the repository with the database, the API endpoint with the service and the database. Unit tests catch logic errors; integration tests catch fit errors. The rest of the post shows what each one catches in practice, with API and database examples.

The difference in one table

Unit test Integration test
Scope One function, method, or class Two or more real parts together (code + database, API + service + database, consumer + queue)
Dependencies Replaced with mocks, stubs, or fakes Real, or as close as possible (database in a container, external service simulated over the network)
Speed Milliseconds per test Tens of milliseconds to seconds per test, plus setup
What it catches Logic errors: calculations, conditional rules, edge cases Fit errors: wrong query, mapping, migration, contract between layers, transactions
What it misses Any problem at the boundary with whatever was mocked Fine-grained logic combinations (too expensive to test all of them there)
When it fails Points to a function Points to a flow; you have to investigate which part
Common tools pytest, JUnit, Vitest, go test The same, plus Testcontainers, a test database, a test HTTP client

What each type of test actually sees

A unit test isolates a unit and verifies its behavior with controlled inputs. Everything outside it is replaced with doubles. The test is fast, deterministic, and surgical — and blind to everything the double hides.

An integration test verifies that components work correctly when coupled. The difference isn't granularity — it's what you're trying to guarantee. A unit test guarantees that a function's internal logic is correct. An integration test guarantees that the function behaves correctly inside the system.

The email bug from the opening wouldn't have been caught by any unit test, no matter how good. The email service had its mocks, the user service had its own. Nobody tested the contact point — the real interface between them.

Cost and speed

Unit tests: fast to write, no infrastructure; run in milliseconds, thousands in seconds; maintenance proportional to the number of mocks — the more you mock, the more the test breaks when the implementation changes, even with no behavior change.

Integration tests: slower to write, because they need setup (database, containers, test data); slower to run, and large suites take minutes; maintenance more stable than unit tests when a refactor doesn't change external behavior.

The math seems to favor unit tests. But there's a hidden variable: the cost of an integration bug in production is far higher than the cost of the test that would have caught it. Teams that only write unit tests tend to have high coverage and deploys that still break real flows. Teams that only write integration tests have slow suites and slow development feedback.

What about the testing pyramid?

Mike Cohn's pyramid puts many unit tests at the base, fewer integration tests in the middle, and few e2e tests at the top. Newer shapes — Kent C. Dodds's trophy on the front-end, Spotify's honeycomb for microservices — give more weight to integration. I explained the model, the ice cream cone anti-pattern, and those alternatives in testing pyramid: what it is and its layers; here, only the question that decides the balance in your project: where do your system's production bugs come from?

When to use unit tests

Domain logic with multiple paths is the natural candidate. If you have a discount function with eight combinations of customer type and purchase value, you want to test all eight in milliseconds — not spin up a database every time.

The post Unit testing: what to test covers that territory in detail. Its conclusion: unit tests deliver the most value when the function is pure, has several paths, and its behavior is stable enough that the test won't break on every refactor. Other good candidates:

  • Parsers and data transformations with edge cases
  • Validations with complex rules
  • Formatting functions (dates, currency, documents) with non-obvious inputs
  • Authorization rules with permission combinations

What's not worth unit testing: anything whose only "logic" is calling something else. A controller that hands off to a service, a repository that just calls the ORM, an adapter that only converts formats — no logic, nothing to test in isolation.

When to use integration tests

Repository and database

The repository is the most obvious case. Mocking the database in a repository test defeats the purpose: you need to know whether the query is right, the mapping is correct, the constraint exists. A repository test that doesn't hit the database is, literally, a mock test.

# This doesn't test the repository — it tests whether you can configure a mock
def test_find_user_mock(mock_session):
    repo = UserRepository(session=mock_session)
    mock_session.execute.return_value = MockResult(fake_user)
    result = repo.find_by_email("test@example.com")
    assert result.email == "test@example.com"

# This tests the repository
def test_find_user_database(db_session):
    repo = UserRepository(session=db_session)
    db_session.add(User(email="test@example.com", name="Test"))
    db_session.commit()
    result = repo.find_by_email("test@example.com")
    assert result.email == "test@example.com"

The second catches real problems: wrong query, a field mapped under another name, a violated constraint, a migration not applied. The first catches none of that.

API + database

This is the case that raises the most questions: should the API endpoint be tested with a mocked or a real database? For the main flow, real. The test calls the endpoint through a test HTTP client, lets the service and repository do their actual work, and checks what was written to the database. I ran this version with FastAPI, SQLAlchemy 2, and pytest against PostgreSQL 18 — two tests, 0.62 s:

@pytest.fixture
def client(db_session):
    # swap only the database session for the test session; everything else is real code
    app.dependency_overrides[get_session] = lambda: db_session
    yield TestClient(app)
    app.dependency_overrides.clear()


def test_create_order_stores_total_in_database(client, db_session):
    resp = client.post("/orders", json={"customer_id": 1, "items": [{"sku": "A1", "qty": 2}]})

    assert resp.status_code == 201
    order = db_session.execute(
        text("SELECT status, total FROM orders WHERE id = :id"), {"id": resp.json()["id"]}
    ).one()
    assert order.status == "pending"
    assert str(order.total) == "39.80"  # 2 x 19.90, computed from the price stored in the database

This test catches what no unit test of the handler would: payload validation, serialization, the price query, the INSERT ... RETURNING, the NUMERIC type coming back as expected. The db_session fixture truncates the tables and inserts product A1 before each test — known data, no shared state. For more patterns along these lines (response contracts, authentication, test data), see how to test APIs in an automated way.

Other cases

  • Queue processing: verify that a published message is consumed and processed, with the real broker in a container.
  • External services: when viable, the real API in a sandbox. When not, a simulated server on the network (WireMock, Prism) that behaves like the service — not an in-code object mock.
  • Transformation pipelines: when data goes through several stages, testing the whole pipeline is usually worth more than each step in isolation.

The most expensive mistake: mocking what should be integrated

There's a pattern that looks prudent and is a trap: mocking the database in repository tests, mocking the email service in notification tests, mocking the external API in payment tests — and never having a test that verifies the real integration.

The result is a suite with 90%+ coverage where every component is "tested" and the system as a whole has never been exercised. The numbers look good; the confidence is false. The post on mocks, stubs, and fakes separates when each kind of double helps and when it hides exactly the bug that matters.

The heuristic I use: if two components are separate in code but coupled in production behavior, the relevant test is an integration test. Layer boundaries, callbacks, events — that's where bugs are born, and exactly what unit tests skip by design.

Infrastructure for integration tests

The biggest argument against integration tests is setup cost. It's real, but solvable. Testcontainers spins up a database container (Postgres, MySQL, Redis, whatever) at the start of the suite and discards it at the end — no shared state between runs and no dependency on a database configured on each developer's machine.

# testcontainers-python 4.x (older versions: from testcontainers.postgres import ...)
from testcontainers.community.postgres import PostgresContainer

@pytest.fixture(scope="session")
def database_url():
    with PostgresContainer("postgres:18", driver="psycopg") as pg:
        yield pg.get_connection_url()  # postgresql+psycopg://...

There are versions for Go (testcontainers-go), Java (the original library), Node, and .NET. Here, with the image already pulled, postgres:18 was ready in 2 to 3 seconds; the first pull costs a lot more. With scope="session", you pay that once per suite.

For third-party APIs, I use contract tests: define what the API receives and returns, test against a simulator that honors that contract, and keep a separate, less frequent test that validates the contract against the real API. The post on contract testing between services details the pattern.

Frequently asked questions

What's the practical difference between integration tests and E2E tests?

An integration test verifies parts of the system working together, usually without a user interface, through code or HTTP. An E2E test drives the whole system through the interface — usually a browser with Playwright or Cypress. Integration tests are faster and easier to debug; E2E tests are closer to the real user but much slower and more brittle. Use E2E for critical flows — the post on when e2e tests are worth it helps pick which.

Can I use in-memory SQLite instead of the production database in integration tests?

Only if the code uses portable SQL. SQLite differs from Postgres in types (flexible typing by default), JSON, upserts, and concurrency; a test that passes on SQLite can fail on Postgres because of dialect differences. If production is Postgres, test with Postgres — Testcontainers makes that simple enough. SQLite shines in other scenarios, which I cover in when to use SQLite.

What's the right ratio of unit, integration, and e2e tests?

There's no universal ratio; fixed percentages like 70/20/10 are a convention, not a rule. Decide by risk: where domain logic is dense (calculations, conditional rules, validations), unit tests pay off more and the classic pyramid describes the suite well; where behavior lives at the boundaries (CRUD APIs, database, queues, microservices), integration tests pay off more and the suite tends toward the honeycomb — it's common for an API back-end to have as many integration tests as unit tests, or more. Either way, e2e tests stay few and reserved for critical flows.

Are mocks bad in integration tests?

Mocks have their place — for external services you don't control (payment gateway, SMS, transactional email), preferably simulated at the network boundary. The problem is mocking internal components you could test for real. If you're mocking your own service inside an integration test, you're probably testing the wrong layer.

Unit and integration tests don't compete, they complement each other

The tension between the two is false. Unit tests handle internal logic problems well; integration tests handle coupling and contract problems between components. A healthy system uses both where each has the advantage. What doesn't work is using one as a substitute for the other out of convenience — mocking everything to get fast tests, or writing only E2E because "it's more realistic." The most expensive production bugs I've seen were all at integration points covered by mocks. Code coverage isn't coverage of real behavior.

One thing that makes integration tests much cheaper is having test data ready. For seeds and sample payloads — customers, orders, products with varied fields — I generate the JSON with the JSON Mock Data Generator and version it alongside the tests.

RD
Author
Rafael Duarte
Backend developer with a background in fintech and B2B SaaS — worked on teams that scaled APIs from zero to millions of requests. Carries enough production scars to hold strong opinions on tools, patterns and architecture decisions. Not an academic: he read the UUID RFC when he had to choose between v4 and v7 for a write-heavy table.
View profile