Sub topic 12
Mocking HTTP Callouts with HttpCalloutMock
This chapter assumes you can write basic Apex test classes, use Assert methods, and understand Test.startTest and Test.stopTest. You should also know how an Apex class makes an HTTP callout with Http, HttpRequest and HttpResponse.
Why tests cannot make real callouts
Apex tests do not send HTTP requests to external systems. If a test runs code that calls new Http().send(req) and no mock is registered, the platform throws a System.CalloutException with the message "Methods defined as TestMethod do not support Web service callouts".
The restriction protects you in three ways:
- Tests do not depend on a remote service being available.
- Tests run the same way every time, because the response is fixed.
- Tests cannot change data in a production system by accident.
The platform gives you a way to supply a fake response. You write a class that implements HttpCalloutMock, then register it with Test.setMock. When the code under test calls send, the platform skips the network and calls your mock.
The shape of a callout test
The code under test is a small client that reads a shipping rate:
public with sharing class ShippingClient {
public static Decimal getRate() {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Shipping_API/rates');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Shipping service returned ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (Decimal) body.get('rate');
}
}The class has a success path and a failure branch. Both need tests. Here is the success test:
@isTest
private class ShippingClientTest {
private class ShippingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"rate": 12.5}');
return res;
}
}
@isTest
static void returnsRateFromService() {
Test.setMock(HttpCalloutMock.class, new ShippingMock());
Test.startTest();
Decimal rate = ShippingClient.getRate();
Test.stopTest();
Assert.areEqual(12.5, rate, 'Rate should come from the mocked response');
}
}Three parts matter:
- The mock class.
HttpCalloutMockhas one method,respond(HttpRequest req). It receives the request your code built and returns theHttpResponsethe code will see. Test.setMock(HttpCalloutMock.class, instance). The first argument is the interface type and the second is your instance. Call it before the code that makes the callout.- The assertion. The test checks the parsed value,
12.5. It does not only check that the code ran.
The mock is a private inner class. That keeps it next to the test that uses it and out of the production code. If several test classes need the same mock, move it to its own @isTest class.
A configurable mock for several scenarios
The first mock always returns a 200 response. Testing the != 200 branch with a second hard-coded class would repeat code. A better approach is one mock that takes the status code and body in its constructor:
@isTest
public class SimpleHttpMock implements HttpCalloutMock {
private final Integer statusCode;
private final String body;
public SimpleHttpMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}Now add the failure test to ShippingClientTest:
@isTest
static void throwsWhenServiceFails() {
Test.setMock(HttpCalloutMock.class, new SimpleHttpMock(503, '{"error":"unavailable"}'));
Test.startTest();
try {
ShippingClient.getRate();
Assert.fail('Expected a CalloutException');
} catch (CalloutException e) {
Assert.isTrue(e.getMessage().contains('503'), 'Unexpected message: ' + e.getMessage());
}
Test.stopTest();
}Assert.fail is the important line. If getRate did not throw, the test would reach Assert.fail and fail. Without it, a missing exception would pass silently. Note that Assert.fail throws an AssertException, which is not a CalloutException, so the catch block does not swallow it.
Checking the request your code sends
The mock receives the request, so it can also verify what the code sent. Assertions inside respond fail the test like any other assertion:
private class RequestCheckingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
Assert.areEqual('GET', req.getMethod(), 'Client should use GET');
Assert.isTrue(req.getEndpoint().endsWith('/rates'), 'Wrong endpoint: ' + req.getEndpoint());
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"rate": 1}');
return res;
}
}This catches bugs where the response parsing is correct but the request is wrong, such as a wrong HTTP method, a missing header, or a malformed body. If the mock was never called, those assertions never ran. For a client that must make a callout, also assert something about the result.
Mocking more than one endpoint
Some code calls several endpoints in one transaction. Test.setMock accepts only one mock per test context, so one mock class has to route by request:
@isTest
private class RoutingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
if (req.getEndpoint().contains('/rates')) {
res.setBody('{"rate": 12.5}');
} else if (req.getEndpoint().contains('/tracking')) {
res.setBody('{"status": "Delivered"}');
} else {
res.setStatusCode(404);
res.setBody('{}');
}
return res;
}
}The final else returns 404 for any URL you did not plan for. An unexpected call then shows up as a failure and not as an empty success.
Salesforce also offers StaticResourceCalloutMock, which returns the body of a static resource, and MultiStaticResourceCalloutMock, which maps endpoints to resources. They suit large JSON payloads that are awkward to write as string literals. The cost is that the response lives in another file, so a reader must open it to understand the test.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Methods defined as TestMethod do not support Web service callouts" | `Test.setMock` was not called, or was called after the callout | Register the mock before the code that calls `send` |
| "You have uncommitted work pending. Please commit or rollback before calling out" | The test did DML and then made a callout in the same transaction | Create the data in `@TestSetup`, which is committed before each test method |
| Test passes but the mock never ran | The code under test took a branch that does not call out | Assert on the result, and use test data that reaches the callout |
| Mock returns data the code cannot parse | The mock body does not match the real API | Copy a real response from the API documentation |
| Wrong mock interface for a SOAP call | `HttpCalloutMock` only covers HTTP | Use `WebServiceMock` for classes generated from a WSDL |
Mocking and asynchronous code
Callouts often happen in Queueable, Batch or future methods. The mock rules do not change. Call Test.setMock first, then enqueue the job between Test.startTest and Test.stopTest. Test.stopTest forces the asynchronous work to finish, and the mock answers the callout inside it. Assert after stopTest. A Batch job that makes callouts must implement Database.AllowsCallouts, or the real class fails in production even when the test passes with a mock.
What to remember
- Real callouts are blocked in tests. Register a mock with
Test.setMockbefore the callout runs. - Implement
HttpCalloutMock.respondand return the response you want the code to see. - Use a configurable mock to cover success and failure paths without duplicate classes.
- Assert on the outcome of the code under test. A mock that runs without any assertion adds coverage but proves little.
- Create DML test data in
@TestSetupto avoid the uncommitted work error.
Exercise
A teammate's test registers a mock that returns status 200 with a valid body, then calls ShippingClient.getRate() and asserts the returned rate. Coverage of ShippingClient is 83%, and the uncovered line is the throw new CalloutException(...) line. Write the test that covers it, and explain why Assert.fail must appear inside the try block.
Show answer
Register new SimpleHttpMock(503, '{"error":"unavailable"}') with Test.setMock. Then, in a try block, call ShippingClient.getRate() followed by Assert.fail('Expected a CalloutException'), and catch CalloutException e. In the catch block, assert that e.getMessage() contains '503'. Assert.fail is needed because if getRate stopped throwing, execution would continue past the call and the test would pass without checking anything. With Assert.fail placed right after the call, a missing exception fails the test. It throws an AssertException, which the CalloutException catch block does not catch.
Exercise
A test creates an Account with insert, then calls a method that makes a callout, and fails with "You have uncommitted work pending". What is the cause, and what is one way to fix it?
Show answer
The platform does not allow a callout after DML in the same transaction until that work is committed. One fix is to move the data creation into a @TestSetup method. Setup data is committed before each test method runs, so the method can query the records and make the mocked callout without the error.