Advanced 20 min read

Mocking Callouts with HttpCalloutMock

By the end of this lesson, you'll be able to:

  • Explain why real HTTP callouts aren't allowed during Apex tests
  • Implement HttpCalloutMock to simulate an external API response

Prerequisites: Testing Bulk Operations

Why callouts are blocked in tests

Tests need to be fast, deterministic, and independent of whether some external system happens to be up right now. A real callout during a test run would be slow, flaky, and could have real side effects on an external system — so Salesforce throws an exception if a test attempts a real callout without a mock registered.

Implementing HttpCalloutMock

Create a class implementing HttpCalloutMock, with one method — respond(HttpRequest req): HttpResponse — that builds and returns a fake HttpResponse. Register it before the code under test runs with Test.setMock(HttpCalloutMock.class, new YourMockClass()).

A simple HttpCalloutMock implementation

@isTest
global class WeatherApiMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"tempCelsius": 22}');
        res.setStatusCode(200);
        return res;
    }
}

This mock never leaves Salesforce's servers — it just hands back a canned response any time the code under test performs a callout during this test.

Exercise

Write a test method that registers WeatherApiMock and calls WeatherService.getTemperature(), asserting it returns 22.

Show hint

Test.setMock(HttpCalloutMock.class, new WeatherApiMock()); must run before the callout happens.

APEX

Mocking Callouts with HttpCalloutMock — Quick Check

1. What happens if Apex test code attempts a real HTTP callout without a mock registered?

2. HttpCalloutMock's respond() method must return a real HttpResponse object your test controls entirely.

3. Which method registers a mock for the duration of a test?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Apex tests can't make real HTTP callouts at all — Salesforce blocks them outright — so testing integration code means implementing the HttpCalloutMock interface to return a fake, predictable response instead.