TEST ARCHITECTURE

Choosing Between Mocking and a Real Test Environment

Every API test suite reaches the same fork: mock the dependency, or run against a real environment? I've seen teams mock everything and end up with a suite that's green every night while production breaks. I've also seen teams refuse to mock anything, then lose days to failures caused by a downstream service that had nothing to do with the change being tested.

Neither extreme is a strategy. Mocks and real environments answer different questions, and the useful skill is knowing which question each test is asking. That decision now has a new dimension. Many APIs call a language model somewhere, and many test suites are being written by coding agents. A mocked model gives you fast, deterministic tests of your own code; a real model is the only way to learn whether the feature actually behaves well. And an agent asked to "add tests" will often mock far more than it should, because mocks make tests pass easily.

Here's what mocks buy you, what they hide, when a real environment is non-negotiable, and the framework I use to put each test on the right side of the line.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

What mocks buy you, and what they silently hide

A mock replaces a dependency with something you control. That gives you three things that are hard to get any other way:

  • Speed and determinism. No network, no shared state, the same result every run.
  • Hard-to-reach cases. Timeouts, 503s, malformed payloads and rate-limit responses on demand.
  • Isolation. A failure points at your code, not at a partner's sandbox having a bad day.

The cost is that a mock encodes your belief about how the dependency behaves. If that belief is wrong, or goes out of date, the mock keeps agreeing with your code while the real service has moved on. Mocks can't catch a renamed field, a changed auth flow, a stricter validation rule or a slower response. They also tend to drift: nobody updates the fake when the real API changes, because nothing fails.

The quietest failure is a mock that mirrors the implementation. If the test stubs exactly the calls the code makes and returns exactly what the code expects, it proves the code calls what it calls. I see this often in AI-generated tests, where the agent reads the implementation and writes mocks to match it.

Here's a mock I'm happy with, because it tests my own handling of a dependency's failure, which is the thing mocks are good at:

import pytest
import requests

from shop.payments import charge, PaymentUnavailable


def test_charge_raises_clear_error_when_gateway_times_out(monkeypatch):
    def fake_post(*args, **kwargs):
        raise requests.Timeout("gateway did not respond")

    monkeypatch.setattr("shop.payments.requests.post", fake_post)

    with pytest.raises(PaymentUnavailable):
        charge(order_id=1, amount=10.0)

For patterns that keep mocks small and honest, see mocking external APIs in pytest without overcommitting.

When a real environment is non-negotiable

Some questions can only be answered against the real thing, or something very close to it:

  • Integration contracts. Does the payload you send actually get accepted? Does the response still look the way your code expects?
  • Auth and permissions. Token issuance, scopes, role-based responses. Faking these is how auth bugs reach production.
  • Data persistence and side effects. Did the write land? Did the event fire? Did the downstream record update?
  • Configuration. Environment variables, feature flags, gateway rules and timeouts only exist in a deployed environment.
  • Your own database. Mocking your own persistence layer in API tests usually hides more than it helps. A real database in a container is cheap now.

A practical middle ground for third-party services is a small number of real calls against the provider's sandbox, run on a schedule or before release, with mocks everywhere else. When the sandbox is down, those tests should report that clearly rather than fail as if your code broke. I go into that in handling third-party API downtime in your test suite.

Mocking a model versus testing against one

If your API calls a language model, the same split applies, but the stakes are different because the real dependency isn't deterministic.

I inject the model call as a plain function, so the code under test depends on generate(prompt) -> str rather than on a vendor SDK. In most tests I pass a fake:

from support.summaries import summarise_ticket


def test_summary_handles_model_returning_empty_text():
    def fake_generate(prompt):
        return ""

    result = summarise_ticket("Printer on floor 3 is jammed", generate=fake_generate)
    assert result.status == "needs_review"


def test_prompt_includes_ticket_text_but_not_customer_email():
    seen = {}

    def fake_generate(prompt):
        seen["prompt"] = prompt
        return "Printer jam reported."

    summarise_ticket("Printer jam. Contact: jo@example.com", generate=fake_generate)
    assert "Printer jam" in seen["prompt"]
    assert "jo@example.com" not in seen["prompt"]

These tests are fast and deterministic, and they check what my code does: how it builds the prompt, what it strips out, how it handles empty, malformed or overlong output. They say nothing about whether the model's summaries are any good.

That question needs the real model, and it needs a different kind of test. I keep a small set of example inputs with clear expectations, run each one several times against the real model, and report a pass rate rather than a single pass or fail. Those tests are marked separately and run on a schedule or when the prompt or model changes, not on every commit. Mixing them into the fast suite gives you a pipeline that fails at random and teaches people to ignore it.

A decision framework for each test

When I'm deciding, or reviewing a test an agent wrote, I ask these questions in order:

  1. Who owns the behaviour being checked? If it's my code's logic, mock the dependency. If it's the interaction with the dependency, use the real thing.
  2. Could the mock be wrong without anything noticing? If yes, there needs to be at least one real test covering the same interaction.
  3. Is this a failure mode I can't trigger for real? Timeouts and 5xx responses are good mock territory.
  4. Is the dependency non-deterministic? Mock it for logic tests; evaluate it for real with repeated runs and a threshold.
  5. Does the mock just restate the implementation? Then delete it, or replace it with a real test.

Put the rule in your repository instructions too, so assistants follow it: mock third-party services and model calls in unit and component tests, never mock our own API or database in API tests, and never add a mock just to make a failing test pass.

The layering view helps here. Mocks belong mostly at the bottom of the suite and real environments at the top; layering a test suite: unit, API, end-to-end shows how I divide the work. If you want to practise this on a real project, my API testing courses build a suite against a live API with VS Code and GitHub Copilot, including the fixtures that make the real-environment tests reliable.