OBLYTECH Logo
OBLYTECH Logo

Mocking External Callouts in Apex Tests Without Live Endpoints

To test Apex code that makes an outbound call without a live endpoint, route the call through a replaceable layer and supply a scripted stub response in its place. Script one response for each outcome the integration must handle: success, error status, malformed body, missing field and a thrown exception. Each test then reaches the same branches production uses.

Why callout tests should not depend on a live endpoint

A test that calls a real service can fail for reasons unrelated to your code. The endpoint may be down, a test credential may have expired, or another team may be changing shared sandbox data while your run is in progress. When the test fails, you have to work out whether the code or the environment is at fault. Stubbing the callout removes that question. The result depends on the code under test and the response you chose to give it.

A second reason matters more over time. A live call returns whatever the remote service sends that day, but bugs tend to hide on the failure paths: a 503 during a maintenance window, a null nested field, or valid JSON in an unexpected shape. A stub can produce each of these on demand.

Put the callout behind a boundary the test can replace

Stubbing is straightforward when the outbound call sits in one place and hard when it is scattered through trigger handlers, controller methods and batch logic. Move the request construction, the send and the parsing into one dedicated class with a narrow entry point. Code above that boundary should not need to know whether the answer came from the remote service or from a test.

A workable boundary has three parts, and it helps to name them in your design notes:

  • A request builder that turns business data into the outbound message, with no side effects of its own.
  • A sender that performs the actual call and is the single piece that touches the network.
  • A parser that converts the raw response into the domain values your code uses, and raises a clear error when the response does not match what it expects.

Keeping the parser separate from the sender is the detail teams often skip. When the two are merged, the parser cannot be tested without making a call, which pulls the test back toward a live endpoint. Separate them, and the parser can be fed a captured or hand-written body directly.

Build one stub response for each branch you need to test

Write down the branches before you write the stub. For an integration that reads a status record from an external system, the list usually looks like this:

  1. The remote system returns a success status and the body matches the expected shape.
  2. The remote system returns a client error, such as a rejected request because a required identifier is missing.
  3. The remote system returns a server error or an unavailable status.
  4. The body is valid, but a field your code depends on is absent or null.
  5. The body cannot be parsed at all.
  6. The call raises an exception before any response arrives.

Give each item its own stub, built explicitly inside the test that uses it. Avoid one generic stub that returns the same success body for each test method. When a single stub serves all the tests, they share an unstated assumption about the response. A change to the expected shape then breaks many tests for one reason, and the error paths go untested.

Name each stub after the branch it represents. A method name that describes the success-with-missing-field case tells the next developer what the test is for.

Test the error branches with the same care as the success path

Check how the code reacts to non-success status codes

Your code probably maps status codes to outcomes: retry, mark the record for review, or show the user an error. Test each mapping separately. A test limited to the success case cannot tell you whether a retry was scheduled, whether the record was flagged, or whether the user saw a message they can act on.

Check how the code handles incomplete bodies

Partial data is a common failure in practice. A remote team adds, renames or drops a field, and the integration keeps running with a blank value that flows into a record update. Write a test in which each required field is missing in turn, and assert that the code stops at the parser with a message that names the missing field. If the code quietly writes an empty string into a record, that is a defect the test should catch.

Check what happens when the call itself fails

An exception thrown during the call is a different path from a bad response. Make sure the stub can simulate it, then confirm that the calling code leaves the transaction in the state the design intends. Settle the intended behavior first, because a test verifies what the design says should happen. If nobody has decided whether a failed sync should block a save or be queued for later, the test will expose that gap rather than close it.

Set up test data so the stubbed flow matches real records

A stub supplies the response, but the code under test still reads records from the test database to decide what to send. Those records need to resemble production closely enough that the request builder receives realistic input. Create them in the test setup rather than relying on whatever already exists in the org, so each test starts from a known state.

Watch for validation logic at this step. If a record the integration writes must pass rules that other code enforces, the test data has to satisfy those rules too, or the test fails for a reason unrelated to the callout. The guide on validation rules that do not break integrations explains how to keep those checks from interfering with system-to-system updates. Read it before you decide where the stubbed flow sits relative to them.

Bulk loading of fixture records is a separate choice, and the trade-offs are laid out in the guide on choosing data loader options for migration.

When test data grows, keep bulk behavior in mind. Code that makes one outbound call per record can run into platform limits as volume rises, even when each individual test passes. The governor limits guide for admins explains the kinds of limits that shape this decision. Write at least one test that runs the flow over a batch, and check whether the code groups work instead of calling once per row.

Keep live endpoint checks in a separate, deliberate step

Stubbed tests confirm that your code reacts correctly to the responses you have written down. They do not confirm that those responses match what the remote system actually sends. Keep a small set of checks that run against a real test endpoint, outside the unit test suite. Run them on a schedule or before a release, not on each build. Those checks are where you confirm that your assumed response shape is still accurate.

Plan where those live checks run before you need them. If the integration points at a non-production system, the copy of the org that talks to it is usually a sandbox, and sandbox copies need their own planning. The sandbox refresh planning guide covers how to schedule refreshes so a live check does not run against data that was just overwritten.

Decide who owns the stubs and how they change

Stubs drift. The developer who wrote the first version moves on, the remote team changes a field, and the stub keeps returning the old shape. The tests still pass because they agree with each other, not with the remote system. Assign an owner to each integration boundary. Put a short note at the top of each stub class that records the date of the last live check and the contract version the stub was written against.

When a contract changes, update the stub, its branches and the parser in the same change, so reviewers see them move together. A change to just the parser fails tests and tempts a quick edit to the stub that hides the real difference.

For help planning this work, see Salesforce implementation.

Questions about stubbing outbound calls in Apex tests

Can one stub class serve several integrations?

It can, but a shared class hides which integration a test is exercising. Give each integration its own stub class, even if the classes share a small helper for building scripted responses. A failing test then points to one boundary, and the class name tells the reader which remote contract it reflects.

How many test cases does an integration need?

There is no fixed number. Start from the branch list and add one case for each distinct outcome your code handles differently. Two error responses that lead to the same handling can share a test, while two that produce different user messages should not. The count follows the branches in the code.

Should the test assert on the exact request body sent to the remote system?

Assert on the parts the remote contract relies on: required fields, identifiers and any values the code derives. Checking each character of a request makes tests brittle when harmless formatting changes. Leave cosmetic ordering alone unless the contract depends on it.

What should a parser do with a field it does not recognize?

Decide the policy first. Many integrations ignore fields they do not use, which keeps them working when the remote side adds data. Others treat an unknown field as a sign that the contract has changed. Write one test for the policy you chose, so a later change to it shows up as a failing test rather than a quiet change in behavior.