Sub topic 4
Implementing HttpCalloutMock
This chapter assumes you can write Apex classes and @IsTest test classes, and that you know HTTP methods, status codes, and JSON. It also assumes you have read the earlier chapters on why tests cannot make real callouts and on the Http, HttpRequest, and HttpResponse classes.
By the end you will be able to write a mock class, shape the response it returns, simulate failures, and avoid the usual mistakes. Registering the mock with Test.setMock is the next chapter. The mock is only half of the setup.
What the interface asks of you
HttpCalloutMock is a built-in interface with one method:
public interface HttpCalloutMock {
HttpResponse respond(HttpRequest req);
}When the code under test calls new Http().send(req) and a mock is registered, the platform doesn't contact the network. It passes your HttpRequest to respond and gives the returned HttpResponse back to the caller. The code under test can't tell the difference. It sees a status code, headers, and a body, exactly as it would from a real server.
sequenceDiagramReplace the placeholder above only if needed. The real diagram follows.
A reusable mock
The tutorial's WeatherServiceMock takes the status code and body through its constructor, so one class covers many scenarios.
@IsTest
public class WeatherServiceMock implements HttpCalloutMock {
private Integer statusCode;
private String body;
public WeatherServiceMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}Four details matter here.
implements HttpCalloutMock. The class must providerespondwith exactly this signature: public or global, returningHttpResponse, taking oneHttpRequest.@IsTeston the class. Test-only classes are excluded from your org's Apex code size limit. They also can't be called from production code by accident.- Constructor state. Fields set in the constructor let each test choose its response. Don't use static variables for this. Shared static state makes tests depend on each other.
publicvisibility. A top-level mock can be shared by many test classes. If only one test class needs it, make it a private inner class instead (shown later).
Shaping the response
respond builds an HttpResponse with setters. The ones you'll use most:
| Method | What it controls | Notes |
|---|---|---|
| `setStatusCode(Integer)` | The numeric status, such as 200 or 500 | Your code probably branches on this. Always set it. |
| `setStatus(String)` | The reason phrase, such as `OK` | Needed only if your code reads `getStatus()`. |
| `setBody(String)` | The response body as text | Use this for JSON, XML, or plain text. |
| `setBodyAsBlob(Blob)` | The body as binary data | Use this when the code calls `getBodyAsBlob()`. |
| `setHeader(String, String)` | A single response header | Set `Content-Type` if the code reads it. |
A freshly created HttpResponse has no status code set. If you forget setStatusCode, a check like res.getStatusCode() != 200 will fail, and the error will look like a bug in your production code. Set it every time.
Match the body to what the production code expects. WeatherService calls JSON.deserializeUntyped and then body.get('condition'). A body of 'Sunny' isn't valid JSON, so deserializeUntyped would throw a JSONException. Mock bodies should be realistic enough to exercise the parsing code, or the test proves little.
Mocks are plain classes
Because respond is an ordinary method, it can do anything Apex allows. Three common uses follow.
Simulating a network failure
A real callout can fail without any HTTP response, for example on a timeout or an unreachable host. In that case Http.send throws a System.CalloutException. Your mock can do the same by throwing it:
@IsTest
public class FailingCalloutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Simulated network failure');
}
}The exception propagates out of Http.send into the code under test, so you can check that your catch blocks and retry logic work.
Branching on the request
The mock receives the request, so it can behave differently depending on what was sent. This mock returns an error for a missing city parameter and a success otherwise:
@IsTest
public class ValidatingWeatherMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
if (req.getMethod() == 'GET' && req.getEndpoint().contains('city=')) {
res.setStatusCode(200);
res.setBody('{"condition":"Cloudy"}');
} else {
res.setStatusCode(400);
res.setBody('{"error":"city is required"}');
}
return res;
}
}Keep this branching small. When a mock grows many branches, it becomes a program that needs its own tests. A later chapter covers a routing mock for the case where one test makes several different callouts.
Recording what was sent
A mock can save the request in a field so the test can inspect it afterwards:
@IsTest
public class RecordingMock implements HttpCalloutMock {
public HttpRequest lastRequest;
public HttpResponse respond(HttpRequest req) {
lastRequest = req;
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"condition":"Sunny"}');
return res;
}
}The test keeps a reference to the mock object it registered and reads lastRequest after the code under test runs. Apex passes object references, so the test and the platform see the same instance.
Inner-class mocks
If one test class is the only user of a mock, define the mock inside it. The mock stays next to the assertions that depend on it:
@IsTest
private class InlineMockExample {
private class SunnyMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"condition":"Sunny"}');
return res;
}
}
@IsTest
static void mockCanBeAnInnerClass() {
HttpCalloutMock mock = new SunnyMock();
HttpResponse res = mock.respond(new HttpRequest());
Assert.areEqual(200, res.getStatusCode(), 'The mock should return 200');
}
}The test above calls respond directly. That is a quick way to check a mock in isolation, but it doesn't test your production code. Real callout tests register the mock instead, which is the next chapter's topic.
Common mistakes
- Returning
null. If a code path inrespondends without returning a response, the calling code receivesnulland typically fails with a null-reference error far from the real cause. Make sure every branch returns anHttpResponse. - Forgetting the status code. See the table above. The default is not 200.
- Invalid or incomplete JSON bodies. A missing brace or unquoted key causes a parsing error in your production code. Write bodies as single-quoted Apex strings with double-quoted JSON keys, and check the quotes.
- Mocking more than needed. If the mock returns every field of a large real response, the test becomes noisy. Include the fields the code reads.
- Putting assertions in
respond. An assertion that fails inside the mock raises an exception inside the callout path. Your production code may catch it, and the failure can be hidden. Record the request and assert in the test method instead. - Expecting the mock to run without registration. Implementing the interface does nothing by itself. Without
Test.setMock, the callout is attempted for real and the test fails with the "Methods defined as TestMethod do not support Web service callouts" error.
Checking your understanding
Exercise
Write a mock class named TimeoutMock that makes any callout fail as if the server never answered. Then explain why this mock is useful for testing WeatherService.getCondition, and what kind of check the test would make.
Show answer
The class is:
@IsTest
public class TimeoutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Read timed out');
}
}
WeatherService.getCondition has no try/catch, so a CalloutException from Http.send propagates to the caller. The test would register the mock, call getCondition inside try/catch (CalloutException e), call Assert.fail if no exception occurs, and assert on the message. The mock covers the failure path that a mock returning a status code can't reach: the network breaking before any response exists.
Exercise
A teammate's mock sets the body to '{"condition":"Sunny"}' but the test fails inside WeatherService with "Unexpected status: 0". What is the likely cause and the fix?
Show answer
The mock never called setStatusCode, so the status code is not 200 and the service throws its WeatherException. Add res.setStatusCode(200); before returning the response.