Sub topic 9
Testing callouts with HttpCalloutMock
This chapter assumes you can write Apex classes and tests, and that you know HTTP status codes and headers. It also assumes you have already seen a callout that uses a callout: endpoint, as in the previous chapter.
Why tests need a mock
Apex tests are not allowed to make real HTTP callouts. If a test runs code that calls new Http().send(req), the test fails with You have uncommitted work pending or Methods defined as TestMethod do not support Web service callouts. Either way, the real service is never reached.
The fix is HttpCalloutMock, an interface with one method, respond. You write a class that implements it and returns a fixed HttpResponse. In the test you register it with Test.setMock. From then on, any callout in that test goes to your mock instead of the network.
This also means a test never needs the Named Credential, the External Credential or a permission set to exist. The mock replaces the whole callout, so these tests check your Apex logic only. They do not check your Setup configuration.
The code under test
This is the class from the previous chapter.
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();
}
}A test with a mock
@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);
}
}The mock does two jobs. It returns a canned response, and it checks the request your code built. Assertions inside respond fail the test if the method, or the callout:Weather_API/ prefix, is wrong. Checking the prefix guards against someone replacing the Named Credential with a hardcoded URL.
Testing the error path
The success path is only half of the behavior. getForecast throws a CalloutException for any status other than 200. Add a second mock that returns a failure, and test that.
@IsTest
private class WeatherServiceErrorTest {
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 throwsOnNon200() {
Test.setMock(HttpCalloutMock.class, new ErrorMock());
Test.startTest();
try {
WeatherService.getForecast('Oslo');
System.assert(false, 'Expected a CalloutException');
} catch (CalloutException e) {
System.assert(e.getMessage().contains('500'));
}
Test.stopTest();
}
}Common mistakes
- Calling
Test.setMockafter the code that makes the callout. Register the mock first. - Forgetting to assert on the request. A mock that ignores
reqcannot catch a wrong endpoint or method. - Assuming a passing test proves the credential works. It does not. Verify Setup by running the callout in a sandbox.
Exercise
Why does a test that calls WeatherService.getForecast succeed even if the user running the test has no permission set access to the external credential principal?
Show answer
Test.setMock replaces the callout with the mock's respond method, so the request never reaches the Named Credential or the External Credential. Principal access is not checked. Only a real callout in an org with the configuration in place exercises it.
Exercise
What does the mock in the success test check about the request, and why is that useful?
Show answer
It asserts that the method is GET and that the endpoint starts with callout:Weather_API/. This catches a changed method or a hardcoded URL that bypasses the Named Credential.