Sub topic 12
Testing callouts with HttpCalloutMock
This chapter assumes you can write a callout with Http, HttpRequest and HttpResponse, and that you know Apex test basics: @isTest, System.assertEquals, and Test.startTest()/Test.stopTest().
Why callouts need a mock
Apex tests cannot make real HTTP callouts. If a test reaches new Http().send(req) without a mock, the platform throws a System.CalloutException with the message "Methods defined as TestMethod do not support Web service callouts". This is intentional. Tests must run without depending on an outside server, and they must give the same result every time.
You fix this with two pieces:
- A class that implements
HttpCalloutMockand returns a cannedHttpResponse. - A call to
Test.setMockthat tells the platform to use that class instead of the network.
Writing the mock
The interface has one method, respond(HttpRequest req). It receives the request your code built, so you can assert on the method, endpoint, headers or body before returning a response.
@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);
}
}Call Test.setMock before the code that makes the callout. Placing it before Test.startTest() is the usual convention.
The mock asserts on the request method, and the test asserts on the parsed result. Together they confirm that TodoClient.create sends a POST and turns the 201 body into a typed Todo.
Testing the failure paths
A mock that always succeeds only covers the happy path. Your error handling needs tests too. Make the mock configurable so one class can serve several scenarios.
@isTest
global class ConfigurableMock implements HttpCalloutMock {
private Integer statusCode;
private String body;
global ConfigurableMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
global HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}
@isTest
private class TodoServiceTest {
@isTest
static void fetchTodoThrowsOnServerError() {
Test.setMock(HttpCalloutMock.class, new ConfigurableMock(500, 'error'));
Boolean threw = false;
Test.startTest();
try {
TodoService.fetchTodo(1);
} catch (TodoService.TodoException e) {
threw = true;
}
Test.stopTest();
System.assert(threw, 'Expected a TodoException for status 500');
}
}Test other statuses the same way, such as 404 and 401. To simulate a network failure, have respond throw a CalloutException yourself.
Testing asynchronous callouts
A Queueable job runs when Test.stopTest() is called. Set the mock first, enqueue the job between startTest and stopTest, and assert afterward.
@isTest
private class TodoSyncJobTest {
@isTest
static void jobRunsWithMock() {
Test.setMock(HttpCalloutMock.class, new ConfigurableMock(200, '{"id":1}'));
Test.startTest();
System.enqueueJob(new TodoSyncJob(1));
Test.stopTest();
System.assert(true, 'Job completed without a callout error');
}
}The job's execute method calls TodoService.fetchTodo, which reaches the mock. The assertion is weak because the job returns nothing. In real code, have the job write a result you can query.
Common errors
| Symptom | Likely cause |
|---|---|
| "Methods defined as TestMethod do not support Web service callouts" | `Test.setMock` was not called, or ran after the callout. |
| Mock assertion fails inside `respond` | The code built a different method, endpoint or body than you expected. |
| Deserialization error in the test | The canned body does not match the fields of your Apex class. |
| Callout error in a test that sets up data first | The DML ran before the callout in the same transaction. Move the setup before `Test.setMock`, or put the callout in `Test.startTest()`/`Test.stopTest()`. |
Exercise
Your test calls a method that makes a callout, and it fails with "Methods defined as TestMethod do not support Web service callouts". You have already written a class that implements HttpCalloutMock. What is the missing step, and where should it go?
Show answer
Call Test.setMock(HttpCalloutMock.class, new YourMock()) before the code that makes the callout runs, usually before Test.startTest(). Writing the mock class alone does not register it with the platform.
Exercise
How would you test that your code throws a custom exception when the server returns a 404?
Show answer
Create a mock (for example ConfigurableMock) whose respond method returns status code 404, register it with Test.setMock, call the method inside a try/catch between Test.startTest() and Test.stopTest(), and assert that the expected exception type was caught.