Sub topic 12
Testing Callouts with HttpCalloutMock
What you need first
This chapter assumes you can write Apex test classes (@isTest, System.assertEquals, Test.startTest and Test.stopTest). It also assumes you have read the earlier chapters on building requests, reading responses and handling errors. The examples reuse TodoService, TodoClient and TodoSyncJob from those chapters.
Why tests cannot make real callouts
Apex tests never send real HTTP requests. If a test reaches Http.send without a mock, the platform stops it with this error:
System.CalloutException: Methods defined as TestMethod do not support Web service calloutsThis rule helps you. Tests that call a live service are slow and fail when the network or the other system is down. They also can't reproduce a 500 response or a timeout on demand. With a mock, you decide exactly what the "remote service" returns, so every branch of your callout code can be tested.
Salesforce also requires 75% code coverage for deployment to production. Callout code with no mock can't run in a test, so it can't be covered.
The HttpCalloutMock interface
HttpCalloutMock is a built-in interface with one method:
HttpResponse respond(HttpRequest req)You write a class that implements it and builds the HttpResponse you want. Then you register the class with Test.setMock(HttpCalloutMock.class, instance). From that point, any Http.send in the same test transaction calls your respond method and gets its response. Nothing goes over the network.
A complete test for the POST callout
This is the mock and test from the plan. The mock asserts on the request it receives, so the test also checks that your code built the request correctly.
@isTest
global class TodoClientMock implements HttpCalloutMock {
global HttpResponse respond(HttpRequest req) {
System.assertEquals('POST', req.getMethod());
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(201);
res.setBody('{"id":201,"userId":1,"title":"Write tests","completed":false}');
return res;
}
}
@isTest
private class TodoClientTest {
@isTest
static void createReturnsTodo() {
Test.setMock(HttpCalloutMock.class, new TodoClientMock());
TodoClient.Todo input = new TodoClient.Todo();
input.userId = 1;
input.title = 'Write tests';
input.completed = false;
Test.startTest();
TodoClient.Todo created = TodoClient.create(input);
Test.stopTest();
System.assertEquals(201, created.id);
System.assertEquals('Write tests', created.title);
}
}Three points about this code:
Test.setMockruns before the code under test. A mock registered after the callout has no effect.- The mock lives in a class marked
@isTest. Such classes don't count against your org's Apex code size limit. - An
assertinsiderespondfails the test if the request is wrong. For example, it catches a wrong HTTP method.
Named Credentials in tests
TodoClient uses the endpoint callout:Todo_API/todos. The mock replaces the whole network step. The test therefore doesn't need the Named Credential to exist or to hold working credentials. If you assert on req.getEndpoint() inside the mock, check for the path with contains('/todos'). That check doesn't depend on how the endpoint string is expanded.
A reusable mock with a configurable status
Writing one mock class per scenario gets repetitive. A mock with a constructor lets one class cover success, client errors and server errors:
@isTest
global class StatusMock implements HttpCalloutMock {
private Integer statusCode;
private String status;
private String body;
global StatusMock(Integer statusCode, String status, String body) {
this.statusCode = statusCode;
this.status = status;
this.body = body;
}
global HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(statusCode);
res.setStatus(status);
res.setBody(body);
return res;
}
}Testing the failure paths
Most callout bugs live in the error branches. Test each one on purpose.
A non-200 status
TodoService.fetchTodo throws TodoException for any status other than 200. This test checks that it does:
@isTest
private class TodoServiceTest {
@isTest
static void successReturnsBody() {
Test.setMock(HttpCalloutMock.class,
new StatusMock(200, 'OK', '{"id":1,"title":"First"}'));
Test.startTest();
String body = TodoService.fetchTodo(1);
Test.stopTest();
System.assert(body.contains('"id":1'));
}
@isTest
static void serverErrorThrows() {
Test.setMock(HttpCalloutMock.class,
new StatusMock(500, 'Server Error', '{}'));
Boolean thrown = false;
Test.startTest();
try {
TodoService.fetchTodo(1);
} catch (TodoService.TodoException e) {
thrown = true;
System.assert(e.getMessage().contains('500'));
}
Test.stopTest();
System.assert(thrown, 'Expected TodoException for a 500 response');
}
}The thrown flag matters. If you put an assertion at the end of the try block, a missing exception would pass silently.
A thrown CalloutException
Real timeouts and connection failures reach your code as a CalloutException thrown from send. A mock can simulate this by throwing from respond:
@isTest
global class TimeoutMock implements HttpCalloutMock {
global HttpResponse respond(HttpRequest req) {
throw new CalloutException('Read timed out');
}
}
@isTest
private class TodoClientFailureTest {
@isTest
static void timeoutPropagates() {
Test.setMock(HttpCalloutMock.class, new TimeoutMock());
TodoClient.Todo input = new TodoClient.Todo();
input.title = 'Will time out';
Boolean thrown = false;
Test.startTest();
try {
TodoClient.create(input);
} catch (CalloutException e) {
thrown = true;
}
Test.stopTest();
System.assert(thrown, 'Expected CalloutException');
}
}If your code catches CalloutException and returns a fallback value or logs a failure, assert on that behavior instead.
Testing asynchronous callouts
A Queueable job doesn't run inside your test method. It runs when Test.stopTest() is called, so the mock must be registered before that point. Put the enqueue between startTest and stopTest:
@isTest
private class TodoSyncJobTest {
@isTest
static void jobCompletesWithMock() {
Test.setMock(HttpCalloutMock.class,
new StatusMock(200, 'OK', '{"id":1,"title":"First"}'));
Test.startTest();
System.enqueueJob(new TodoSyncJob(1));
Test.stopTest();
// The job has now run. An unhandled exception in execute()
// would have failed this test.
System.assertEquals(1, [SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'Queueable'
AND ApexClass.Name = 'TodoSyncJob'
AND Status = 'Completed']);
}
}TodoSyncJob only writes to the debug log, so the test can't assert on a returned value. Checking AsyncApexJob confirms that the job ran to completion. If your job saves the response to a record, query that record and assert on it instead. The same pattern works for @future(callout=true) methods.
Mocking from static resources
When a response body is large, put the JSON in a static resource instead of a string literal in your test. StaticResourceCalloutMock is a built-in HttpCalloutMock that returns the resource's content:
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('TodoResponse');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, mock);TodoResponse is the name of a static resource in the org. For code that makes several different callouts in one transaction, MultiStaticResourceCalloutMock maps endpoints to resources. Alternatively, write your own mock whose respond method branches on req.getEndpoint() and req.getMethod().
Common test errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Methods defined as TestMethod do not support Web service callouts` | No mock registered, or `Test.setMock` ran after the callout | Call `Test.setMock` first |
| `You have uncommitted work pending. Please commit or rollback before calling out` | DML ran earlier in the same transaction | Create data in `@testSetup`, or run the callout in a Queueable between `startTest` and `stopTest` |
| Assertion on the response body fails | The mock body is not what the code parses (wrong field names or invalid JSON) | Copy the body from a real response and check it is valid JSON |
| Test passes but the error branch never runs | The mock always returns 200 | Add a second test with a 4xx or 5xx mock |
| Async job never seems to run | The enqueue was outside `startTest` and `stopTest` | Enqueue between them |
What a good callout test suite covers
For each callout method, aim for these cases:
- A success response, with assertions on the parsed result.
- At least one error status, such as 400 or 500, and the exception or fallback it should produce.
- A thrown
CalloutException. - An empty or unexpected body, if your parsing code could fail on it.
- For async code, a run through
Test.startTestandTest.stopTest.
Exercise
A test calls TodoClient.create(...) and fails with "Methods defined as TestMethod do not support Web service callouts". The test class does contain a class that implements HttpCalloutMock. What is the most likely cause, and how do you fix it?
Show answer
The mock class exists, but the test never registered it, or it called Test.setMock after the callout. Call Test.setMock(HttpCalloutMock.class, new TodoClientMock()) before the line that calls TodoClient.create.
Exercise
Write a test that proves TodoService.fetchTodo throws TodoException when the server returns 404. Which mock do you use, and how do you make sure the test fails if no exception is thrown?
Show answer
Use StatusMock(404, 'Not Found', '{}') with Test.setMock. Set a Boolean thrown = false, call fetchTodo inside try, and set thrown = true in catch (TodoService.TodoException e). After the try/catch, call System.assert(thrown, 'Expected TodoException'). Without the flag, a missing exception would let the test pass.
Exercise
Why does a test for a Queueable that makes a callout put System.enqueueJob between Test.startTest and Test.stopTest?
Show answer
The job doesn't run during the test method. Test.stopTest forces queued asynchronous work to run synchronously at that point. The mock must already be registered, so the callout inside execute is mocked. Any exception in execute then surfaces in the test.