Sub topic 12
Mocking HTTP Callouts with HttpCalloutMock
This chapter assumes you can write a basic Apex test class, use the Assert class, and call Test.startTest and Test.stopTest. You should also know what an HTTP callout is: Apex sending a request to an external web service.
Why tests cannot make real callouts
Apex tests are not allowed to make real HTTP callouts. If a test runs code that calls Http.send without a mock in place, the test fails with a System.CalloutException saying that callouts are not allowed in tests. The restriction exists for good reasons. Tests must be repeatable, must not depend on an outside service being up, and must not change data in other systems.
The fix is to give the platform a fake response. You write a class that implements the HttpCalloutMock interface. You then register it with Test.setMock. When the code under test calls Http.send, Salesforce skips the network and returns your fake response.
The code under test
ShippingClient calls a named credential endpoint, checks the status code, and reads a rate from the JSON body.
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');
}
}Writing the mock and the test
The interface has one method, respond, which receives the request and returns a response. The mock is usually a private inner class of the test class.
@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');
}
}Call Test.setMock before the code that makes the callout. The assertion checks the parsed value, so the test would fail if the parsing were wrong. A test that only called getRate() would cover the same lines and prove nothing.
Testing the failure path
A mock can return any response, so you can test error handling that a real service rarely triggers. Make the status code a constructor argument and reuse one mock class for several cases.
@isTest
private class ShippingClientErrorTest {
private class StatusMock implements HttpCalloutMock {
private Integer statusCode;
public StatusMock(Integer statusCode) {
this.statusCode = statusCode;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setBody('{}');
return res;
}
}
@isTest
static void throwsWhenServiceFails() {
Test.setMock(HttpCalloutMock.class, new StatusMock(500));
try {
ShippingClient.getRate();
Assert.fail('Expected a CalloutException');
} catch (CalloutException e) {
Assert.isTrue(e.getMessage().contains('500'), 'Unexpected message: ' + e.getMessage());
}
}
}Common errors
| Symptom | Likely cause |
|---|---|
| "Methods defined as TestMethod do not support Web service callouts" | No mock registered before the callout. Call `Test.setMock` first. |
| Mock never runs | The code under test does not reach `Http.send`, for example because an earlier branch returned. |
| Callout fails after DML in the same test | Uncommitted work pending. Perform DML before `Test.startTest`, or make the callout after `Test.startTest`, so the pending-work rule does not apply. |
| Test passes but checks nothing | No assertion on the result. Assert on the parsed value or the expected exception. |
Exercise
A test calls a method that uses Http.send and fails with a callout error. The test class already has a class that implements HttpCalloutMock. What is missing, and why must the test also assert on the result?
Show answer
The test never registers the mock with Test.setMock(HttpCalloutMock.class, new YourMock()) before calling the method, so the platform tries a real callout, which tests do not allow. The assertion is needed because the mock only supplies a response. Without an assertion, the test would cover the lines without verifying that the code parsed the response correctly.