Testing Backend Code

Checking one small piece of logic on its own versus checking that a real request flows correctly through the whole app.

What is it?

As a backend grows, checking by hand (clicking around or sending requests yourself) gets slower and less reliable with each feature. Automated tests do that checking quickly and repeatedly. But tests differ in what they check and how much of the app they cover.

A unit test checks one small piece of logic, usually a single function, on its own. It often replaces dependencies with fakes (see dependency injection) so it tests only that function.

An integration test sends a real request through the running app (routing, middleware, and often a real or realistic test database) and checks that the whole chain gives the right result.

Explain like I'm 10

A unit test is like testing one car part on a bench: does this brake pad grip under pressure? An integration test is a test drive of the assembled car: you check that the brakes, engine and steering work together as a system.

Examples

A unit test — one function, in isolation

function calculateDiscount(price, percentOff) {
  if (percentOff < 0 || percentOff > 100) {
    throw new Error("Invalid discount percentage");
  }
  return price - (price * percentOff) / 100;
}

test("applies a 20% discount correctly", () => {
  expect(calculateDiscount(100, 20)).toBe(80);
});

test("rejects an invalid discount percentage", () => {
  expect(() => calculateDiscount(100, 150)).toThrow();
});

This test never starts a server or touches a network. It calls the function and checks the result, so it's very fast and focused.

An integration test — a real request through the app

const request = require("supertest");
const app = require("../app");

test("GET /products/:id returns the requested product", async () => {
  const res = await request(app).get("/products/42");

  expect(res.status).toBe(200);
  expect(res.body).toMatchObject({ id: "42" });
});

test("GET /products/:id returns 404 for a missing product", async () => {
  const res = await request(app).get("/products/does-not-exist");
  expect(res.status).toBe(404);
});

This test sends a real HTTP request through the app's routing and middleware and checks the full response as a client would see it, not just one internal function.

The same integration test, in FastAPI with pytest

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_get_existing_product():
    response = client.get("/products/42")
    assert response.status_code == 200
    assert response.json()["id"] == 42

def test_get_missing_product_returns_404():
    response = client.get("/products/does-not-exist")
    assert response.status_code == 404

TestClient wraps a FastAPI app the way supertest wraps an Express app. It sends real requests through routing, dependencies and validation, and lets you assert on the real response, without a live server.

How it works

Unit tests call a function or method directly, usually with fake dependencies (see dependency injection), so the test stays fast, isolated and unaffected by anything outside that function.

Integration tests run through the app as a whole, usually by simulating an HTTP request against the real routing and middleware, often with a real but test-only database. They check that the pieces really work together.

Why does it exist?

Unit tests alone can all pass while the app is broken: if two correct functions are wired together wrongly, no unit test catches it. Integration tests alone are slower, and a failure may not tell you which function is at fault.

The two catch different problems at different speeds. A healthy suite has many fast unit tests plus fewer integration tests for the critical paths.

When to use it

Write unit tests for business logic, especially logic with several branches or edge cases (like a discount calculation or validation rule). Write integration tests for critical paths users actually take end to end, like signing up, logging in or placing an order.

When not to use it

Don't write an integration test for something a unit test checks just as well, faster and more reliably. Starting the whole app to check that a pure calculation returns the right number is wasted overhead.

Common mistakes

  • Writing only unit tests and never checking that the pieces work when wired together.

  • Writing only integration tests, giving a slow suite where a failure is hard to trace to its cause.

  • Letting integration tests call real external services (a real payment provider or third-party API) instead of test doubles, making the suite flaky and slow.

Practice exercises

  1. Easy:

    Write a unit test for an isValidEmail(email) function, covering a valid and an invalid case.

  2. Medium:

    Write an integration test for a POST /login route that checks it returns 200 with valid credentials and 401 with invalid ones.

  3. Hard:

    Describe a case where all unit tests pass but an integration test fails, and what that reveals about where the bug lives.

Interview questions

What's the difference between a unit test and an integration test?

A unit test checks one isolated piece of logic, usually with fake dependencies. An integration test checks that several real parts of the app (routing, middleware, often a database) work together.

Why might all unit tests pass while the app is still broken?

Unit tests check pieces in isolation. If the pieces are wired together wrongly, no single unit test catches it, because no single piece is broken.

Why do integration tests typically run slower than unit tests?

They run more of the real system (routing, middleware, often a real or realistic database) instead of one function, so each test does more work.

What is a test double, and what are the main kinds?

Anything that stands in for a real dependency in a test. The main kinds: stubs (return canned values), mocks (record calls so you can assert on them), fakes (simplified but working implementations), and spies (wrap a real function and observe calls).

What's the difference between a stub and a mock?

A stub returns preset responses and doesn't check how it was called. A mock records calls so the test can assert on them, like 'was called exactly once with these arguments.'

What is a spy, as distinct from a mock?

A spy wraps a real function and records how it was called, optionally still running the real implementation. A mock usually replaces the real implementation entirely.

What does supertest actually do when you call `request(app).get(...)`?

It runs the real Express app in memory and sends a real HTTP request through its routing and middleware, then returns the actual response, without binding to a network port.

In the FastAPI example, what does `TestClient(app)` let you do that hitting a live server wouldn't?

Send requests straight to the app object in-process, exercising its real routing, dependency injection and validation, with no live server process or open port.

In the FastAPI test, why does `test_get_missing_product_returns_404` assert on a status code instead of expecting an exception?

The handler is expected to handle 'not found' itself and return a 404 response, not let an exception escape. The test checks the API's documented failure-path contract.

What is the test pyramid, and what shape does it describe for a healthy test suite?

A large base of fast, cheap unit tests, a smaller middle layer of integration tests, and very few slow end-to-end tests. Bugs are usually cheaper and faster to catch lower down the pyramid.

Why is `calculateDiscount` from the example a good candidate for a unit test specifically?

It's pure: the same input always gives the same output, with no network or database. Calling it directly fully checks its behavior with no setup.

What makes a test flaky, and why is that a serious problem?

A flaky test sometimes passes and sometimes fails on the same code, usually because it depends on something non-deterministic like real timing or network calls. It erodes trust in the suite, so failures get re-run instead of investigated.

Why do integration tests typically run against a real but test-only database, rather than the production one?

Tests can create, change and delete data without corrupting real user data, and the suite can start from a known, resettable state every run.

What is test isolation, and why does it matter across a suite?

Each test is independent of side effects from other tests, so tests can run in any order, in parallel, or alone. One failure shouldn't cause unrelated failures elsewhere.

Scenario: a signup endpoint's test suite starts failing whenever the tests run in a different order. What does that suggest?

The tests probably share state, e.g. relying on a row an earlier test inserted, or not cleaning the database between runs. That's a test isolation problem, not necessarily a bug in signup.

What is arrange-act-assert, as a structure for writing a test?

Arrange sets up inputs, fakes or state. Act calls the function or makes the request. Assert checks the outcome against what's expected. It keeps tests readable and focused.

Why is `expect(() => calculateDiscount(100, 150)).toThrow()` written with a wrapping function instead of calling `calculateDiscount(100, 150)` directly inside `expect`?

Calling it directly would throw on that line, before the test framework can catch it. Wrapping it lets the framework call it and catch the expected exception.

What is code coverage, and what's a common misconception about it?

The percentage of code the test suite runs. The misconception is that high coverage proves correctness. A line can run without its output ever being asserted, so coverage measures exposure to tests, not how well they check.

Why test a login route's 401 response, rather than only its success case?

Rejecting bad credentials is as much a part of the endpoint's contract as accepting good ones. Untested failure paths are a common source of security and correctness bugs.

What's a mocking library's role when testing code that calls an external HTTP API?

It intercepts the outgoing call and returns a controlled, preset response instead of using the network. The test stays fast, deterministic, and independent of the third party's availability.

Trap: a test mocks every database call so it always returns success, and the test passes — but the real integration is broken. What does this reveal?

Over-mocking, even in a test meant to be an integration test, can hide real wiring or contract mismatches. Some tests must use the real (or a realistic) dependency to prove things integrate correctly.

Why does FastAPI's `TestClient` behave 'the same way supertest wraps an Express app'?

Both send a simulated HTTP request straight into the real app object in-process, exercising the real routing, middleware and validation, without starting a network server.

What is a snapshot test, and what's a risk of relying on it too heavily?

It saves some output on the first run, and later runs compare against it. The risk is developers 'updating the snapshot' whenever it changes without checking the new output is correct, turning the test into a rubber stamp.

How would you unit test a function that checks 'has this session expired?' without it being flaky?

Pass the current time in as a parameter instead of calling Date.now() inside (see dependency injection). The test can then use a fixed timestamp and assert deterministic behavior around it.

What's the practical tradeoff of writing an integration test for something a unit test could verify just as well?

It runs slower and needs more setup, like a running app and test database. When it fails, a broken piece buried in a long request/response chain is harder to find than with a focused unit test.

Why is a suite with many end-to-end tests and almost no unit tests usually a sign of a problem?

It inverts the test pyramid. The suite is slow, and a failing test only shows that something in a long chain broke, not which piece, so failures are much harder to pinpoint.

Debugging: an integration test for `GET /products/:id` passes locally but fails in CI with a connection error. What's a likely cause?

Something the test needs isn't available in CI as it is locally: e.g. no test database is running or seeded, or the app under test was never started before the request was sent.

Beyond speed, what does letting integration tests depend on real external services cost a suite?

The suite's pass/fail result then depends on that service's uptime, rate limits and data, which adds nondeterminism. It can also cause real side effects, like charging a card or sending a real email, just by running tests.

Why might you choose an in-memory fake database over a plain mock for testing a repository layer?

A fake really implements query and storage behavior, even if simplified, so it can catch bugs in how the repository queries or filters data. A mock returning canned values doesn't exercise that logic.

Follow-up: after adding dependency injection to `chargeCustomer(order, paymentService)`, what specifically becomes testable that wasn't before?

The function's own logic (what to charge, how to handle the service's responses and errors) can be tested with a fake payment service, without a real charge or the real provider being reachable.