Sub topic 9
Testing callouts with HttpCalloutMock
This chapter assumes you can write Apex classes and test methods, know how an HTTP request and response are structured, and have read the earlier chapters on the callout: endpoint syntax. You will learn how to test callout code without reaching the real service, how to check the request your code builds, and how to cover failure paths.
Why tests cannot make real callouts
Apex test methods are not allowed to send real HTTP requests. If a test reaches Http.send without a mock registered, the platform throws a System.CalloutException with the message "Methods defined as TestMethod do not support Web service callouts".
This restriction is useful for three reasons:
- Tests stay fast and repeatable. They do not depend on the network or on the external service being up.
- Tests can produce responses that are hard to get from a real service, such as a 500 error or a malformed body.
- Tests do not need the Named Credential to be authenticated. A mock replaces the whole callout, so no token or API key is used.
That last point matters for this tutorial. A mocked test never exercises the External Credential, the principal, or the permission set. It only proves that your Apex builds the right request and handles the response correctly. The setup in Salesforce Setup still has to be checked by hand or in a sandbox.
The HttpCalloutMock interface
HttpCalloutMock is an interface with one method:
HttpResponse respond(HttpRequest req)You write a class that implements it. When the code under test calls Http.send, the platform does not contact the network. It calls respond on your mock, passes it the HttpRequest your code built, and returns the HttpResponse you produce.
You activate the mock with Test.setMock(HttpCalloutMock.class, mockInstance). Call it before the code that makes the callout.
A first test
This is the service class from the earlier chapter, which uses the callout:Weather_API endpoint.
public with sharing class WeatherService {
public static String getForecast(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Weather_API/forecast?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Weather API returned status ' + res.getStatusCode());
}
return res.getBody();
}
}And its test:
@IsTest
private class WeatherServiceTest {
private class WeatherMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
System.assertEquals('GET', req.getMethod());
System.assert(req.getEndpoint().startsWith('callout:Weather_API/'));
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"temp":21}');
return res;
}
}
@IsTest
static void returnsResponseBody() {
Test.setMock(HttpCalloutMock.class, new WeatherMock());
Test.startTest();
String body = WeatherService.getForecast('Oslo');
Test.stopTest();
System.assertEquals('{"temp":21}', body);
}
}Three details are worth noticing.
- The mock is a private inner class. It only serves this test, so it does not need to be visible elsewhere.
- The assertions inside
respondcheck the request. The endpoint must start withcallout:Weather_API/. If someone replaces it with a hardcoded URL, the test fails. This protects the design from the first chapters of this tutorial. - The test asserts on the returned body, which proves the response was passed back to the caller.
What the endpoint looks like inside the mock
In a test, the request passed to respond still holds the endpoint exactly as your code set it. The mock does not see the resolved base URL from the Named Credential, because no resolution happens. So you assert on the callout: form, not on https://api.example.com/v1.
This also means a typo in the Named Credential name, such as callout:Weather_Api, does not fail a mocked test unless you assert on the name. Assert on the full prefix to catch it.
Flow of a mocked callout
Testing failure paths
The success path is only one branch. getForecast throws a CalloutException for any status other than 200, and that branch needs coverage. A flexible mock lets you choose the status code per test.
@IsTest
private class WeatherServiceErrorTest {
private class StatusMock implements HttpCalloutMock {
private Integer status;
private String body;
public StatusMock(Integer status, String body) {
this.status = status;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(status);
res.setBody(body);
return res;
}
}
@IsTest
static void throwsOnServerError() {
Test.setMock(HttpCalloutMock.class, new StatusMock(500, 'error'));
Test.startTest();
try {
WeatherService.getForecast('Oslo');
System.assert(false, 'Expected a CalloutException');
} catch (CalloutException e) {
System.assert(e.getMessage().contains('500'));
}
Test.stopTest();
}
}The constructor takes the status and body, so one class covers 401, 404, 429 and 500 cases. The System.assert(false, ...) line fails the test if no exception is thrown. Because that assertion throws an AssertException, which is not a CalloutException, the catch block does not swallow it.
Other ways to supply a mock
| Approach | Use it when |
|---|---|
| Inner class implementing `HttpCalloutMock` | One test class needs a simple fixed response. |
| Parameterized mock class (as above) | You want to vary status or body between tests. |
| `StaticResourceCalloutMock` | The response body is large and you would rather keep it in a static resource. |
| `MultiStaticResourceCalloutMock` | The code calls several endpoints and each needs its own canned response. |
For a class that makes more than one callout, a single mock can branch on req.getEndpoint() and req.getMethod() and return a different response for each.
Common mistakes
- Calling
Test.setMockafter the callout. The mock must be registered first, or the platform raises the "do not support Web service callouts" error. - Doing DML before a callout in the same transaction. Salesforce raises an "uncommitted work pending" error if you insert or update records and then call out. In a test, put setup DML before
Test.startTest(). ThestartTestcall gives the code under test a fresh context, which avoids this error for the setup data. - Asserting on the resolved URL. The mock sees
callout:Weather_API/..., not the real host. - Treating a green test as proof the credential works. The mock bypasses the External Credential and the permission set. A test cannot show that a user has principal access.
- Mocks that only return 200. Untested error branches are where production incidents come from.
Checking more than the status
A mock can also verify details of the request that matter for security and correctness:
- The endpoint starts with
callout:, so no secret or raw URL is in code. - No
Authorizationor API key header is set in Apex. When the Named Credential injects authentication, the code should not set it. You can assertreq.getHeader('Authorization') == null. - The query string is encoded. For a city such as
New York, assert that the endpoint containsNew+YorkorNew%20York, depending on howEncodingUtil.urlEncodeencodes it. - The method and content type match what the API expects.
Exercise
Your test calls WeatherService.getForecast('Oslo') and fails with "Methods defined as TestMethod do not support Web service callouts". What is missing, and where must it go? After you fix it, why does the test still say nothing about whether the Weather_PI permission set grants the user access?
Show answer
The test is missing Test.setMock(HttpCalloutMock.class, new WeatherMock()), or the call is placed after the callout. It must run before the code that calls Http.send, usually as the first statement of the test method. Once it is in place, the mock answers the request inside Apex, so the Named Credential, External Credential, principal and permission set are never used. The test checks only the request your code builds and how it handles the response.
Exercise
Write the one assertion you would add inside a mock's respond method to confirm the Apex code does not set its own Authorization header, and say why that check fits a Named Credential design.
Show answer
System.assertEquals(null, req.getHeader('Authorization'));. With a Named Credential, the External Credential supplies authentication at callout time. A header set in Apex would suggest a secret or token is handled in code, which defeats the purpose of the credential setup.