Sub topic 11
Mocking HTTP callouts
Apex tests cannot make real HTTP requests. If code under test calls an external service and no mock is registered, the test fails with a "Methods defined as TestMethod do not support Web service callouts" error. This chapter shows how to register a mock response so the callout code runs, and how to assert on the result.
This chapter assumes you can write an @IsTest method, use Assert.areEqual, and know what Test.startTest and Test.stopTest do. You should also know the basics of the Http, HttpRequest, and HttpResponse classes.
How the mock works
You write a class that implements the HttpCalloutMock interface. The interface has one method, respond, which receives the outgoing HttpRequest and returns an HttpResponse. You then call Test.setMock(HttpCalloutMock.class, yourMock) before the code under test runs. When that code calls new Http().send(req), Apex does not leave the platform. It calls your respond method and hands back the response you built.
A class to test
A mock is only useful when real code makes the callout. This service wraps a weather request and parses the temperature from the JSON body.
public class WeatherService {
public static Integer getTemperature() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/weather');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Weather service returned ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (Integer) body.get('temp');
}
}In a real org, the endpoint host must also be registered as a Remote Site or reached through a Named Credential. Tests do not need that setup, because the mock intercepts the call.
A success test
The mock is a private inner class of the test class. The test registers it, calls the service, and asserts on the parsed value.
@IsTest
private class WeatherServiceTest {
private class SuccessMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"temp":21}');
return res;
}
}
@IsTest
static void returnsTemperature() {
Test.setMock(HttpCalloutMock.class, new SuccessMock());
Test.startTest();
Integer temp = WeatherService.getTemperature();
Test.stopTest();
Assert.areEqual(21, temp, 'Temperature should be parsed from the mocked body');
}
}Assert on what your code produces from the response, not on the mock itself. Asserting that a mock returns the status code you just set proves nothing about your code.
Testing the failure path
Real services fail. Add a second mock that returns an error status, and use the negative-testing pattern from the previous chapters. Add the mock and the test inside WeatherServiceTest.
private class ErrorMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(500);
res.setBody('{"error":"server"}');
return res;
}
}
@IsTest
static void serverErrorThrows() {
Test.setMock(HttpCalloutMock.class, new ErrorMock());
try {
Test.startTest();
WeatherService.getTemperature();
Test.stopTest();
Assert.fail('Expected CalloutException for a 500 response');
} catch (CalloutException e) {
Assert.isTrue(e.getMessage().contains('500'), 'Message should include the status code');
}
}Making one mock serve several requests
When the code makes several callouts, one mock class can inspect the request and choose a response. This keeps the test readable.
private class RoutingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
if (req.getEndpoint().endsWith('/weather')) {
res.setStatusCode(200);
res.setBody('{"temp":21}');
} else {
res.setStatusCode(404);
}
return res;
}
}You can also assert on the request inside respond, for example with Assert.areEqual('GET', req.getMethod(), 'Method should be GET'). A failed assertion there fails the test.
Common errors
| Symptom | Likely cause |
|---|---|
| "Methods defined as TestMethod do not support Web service callouts" | `Test.setMock` was not called before the callout, or was called after it. |
| "You have uncommitted work pending" | The test did DML before the callout in the same transaction. Do the DML in `@TestSetup`, or move it after the callout. |
| Assertion on body fails with null | The mock did not call `setBody`. |
| Wrong mock used | A later `Test.setMock` call replaced the earlier one. |
Exercise
A test registers a mock with Test.setMock, but the test fails with "You have uncommitted work pending. Please commit or rollback before calling out." What is the cause, and how do you fix it?
Show answer
The test method performed DML (for example, inserting an Account) before the callout in the same transaction, and Salesforce does not allow a callout after uncommitted DML. Move the data creation into a @TestSetup method, which commits before the test method starts, or perform the DML after the callout.
Exercise
Write the body of a respond method that returns a 404 status with the body '{"error":"not found"}'.
Show answer
HttpResponse res = new HttpResponse(); res.setStatusCode(404); res.setBody('{"error":"not found"}'); return res;