Sub topic 3
Writing callout code that is easy to test
This chapter assumes you can read and write basic Apex classes and @IsTest methods. It also assumes you know the Http, HttpRequest, and HttpResponse classes from the previous chapter, and that you are comfortable with HTTP status codes and JSON. You will not write a mock yet. That comes in the next chapter. First you will shape the code so the mock, and every test after it, stays small.
Why design matters before you write the mock
Test code can only reach what the production code exposes. A single method that builds a request, sends it, checks the status, parses JSON, and updates records can only be tested end to end. Every test then needs a mock, a full response body, and a long setup. When one test fails, you do not know which step broke.
If you split the method into small steps, most of the logic needs no mock at all. Only the step that calls Http.send does.
The seam is already built in
In many languages you make code testable by hiding the network client behind an interface and injecting a fake. In Apex you usually do not need to. Test.setMock intercepts Http.send at the platform level, so the line new Http().send(req) is already a seam.
This means you do not have to wrap Http in your own interface. The design work is about everything around that line:
- Keep the
sendcall in one place. - Move request building and response parsing out of it.
- Make the inputs to each step explicit.
A first design: everything in one method
Here is the service from the plan.
public with sharing class WeatherService {
public class WeatherException extends Exception {}
public static String getCondition(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/weather?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 WeatherException('Unexpected status: ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('condition');
}
}It works, and the plan's later tests cover it well. But it has gaps:
- A blank city produces a request for
?city=. Ifcityisnull,urlEncodethrows a less helpful error. - A response that is not JSON throws a raw
JSONException, and callers must know to catch it. - Checking that the
Acceptheader is set requires a mock and a full call. - The endpoint is hard-coded in the middle of a method.
A refactored design
The version below keeps the same public method and behavior. It splits the work into three steps.
public with sharing class WeatherService {
public class WeatherException extends Exception {}
@TestVisible
private static final String BASE_URL = 'https://api.example.com/weather';
public static String getCondition(String city) {
HttpRequest req = buildRequest(city);
HttpResponse res = send(req);
return parseCondition(res);
}
@TestVisible
private static HttpRequest buildRequest(String city) {
if (String.isBlank(city)) {
throw new WeatherException('City is required');
}
HttpRequest req = new HttpRequest();
req.setEndpoint(BASE_URL + '?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(10000);
return req;
}
private static HttpResponse send(HttpRequest req) {
return new Http().send(req);
}
@TestVisible
private static String parseCondition(HttpResponse res) {
if (res.getStatusCode() != 200) {
throw new WeatherException('Unexpected status: ' + res.getStatusCode());
}
try {
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('condition');
} catch (JSONException e) {
throw new WeatherException('Response was not valid JSON: ' + e.getMessage());
}
}
}What changed and why:
buildRequesttakes plain input and returns anHttpRequest. It never touches the network, so tests can inspect the request directly.sendholds the onlyHttp.sendcall. It is the single place that needs a mock.parseConditiontakes anHttpResponseand returns a value. A test can construct that response by hand.@TestVisiblelets test classes call the private methods without making them part of the public API.BASE_URLis one named constant, so the endpoint is not buried in logic.setTimeoutis explicit. The default is 10 seconds, and the maximum is 120 seconds. Stating the value documents the intent.
Testing the pure steps without a mock
Because buildRequest and parseCondition make no callout, their tests need no Test.setMock call. You can create an HttpResponse yourself with setStatusCode and setBody.
@IsTest
private class WeatherServiceDesignTest {
@IsTest
static void buildRequestSetsMethodHeaderAndEncodedCity() {
HttpRequest req = WeatherService.buildRequest('Oslo');
Assert.areEqual('GET', req.getMethod());
Assert.areEqual('application/json', req.getHeader('Accept'));
Assert.areEqual(
WeatherService.BASE_URL + '?city=' + EncodingUtil.urlEncode('Oslo', 'UTF-8'),
req.getEndpoint()
);
}
@IsTest
static void buildRequestRejectsBlankCity() {
try {
WeatherService.buildRequest(' ');
Assert.fail('Expected a WeatherException');
} catch (WeatherService.WeatherException e) {
Assert.areEqual('City is required', e.getMessage());
}
}
@IsTest
static void parseConditionReadsConditionField() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"condition":"Snow"}');
Assert.areEqual('Snow', WeatherService.parseCondition(res));
}
@IsTest
static void parseConditionRejectsInvalidJson() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('<html>Gateway error</html>');
try {
WeatherService.parseCondition(res);
Assert.fail('Expected a WeatherException');
} catch (WeatherService.WeatherException e) {
Assert.isTrue(e.getMessage().startsWith('Response was not valid JSON'));
}
}
}These tests run fast and fail for one reason each. If parseConditionReadsConditionField fails, the parsing is wrong. The network and the mock are not involved.
The mocked end-to-end tests still matter. They prove the three steps work together and that send really goes through Http. You will write them in the next chapters.
Design rules for testable callout code
| Concern | Design choice | Effect on tests |
|---|---|---|
| Request construction | Build in a method with plain inputs and an `HttpRequest` return value | Assert on method, headers, and endpoint with no mock |
| Sending | One method contains `Http.send` | One place to cover with a mock |
| Response handling | Method takes an `HttpResponse` and returns a value or throws | Test each status code and body without a callout |
| Endpoint | A named constant, or a Named Credential endpoint of the form `callout:Name/path` | No URL copies scattered through the code |
| Errors | Throw a typed exception with the status code in the message | Tests can catch one type and check the message |
| Return value | Return a value or a small wrapper class, not a raw `HttpResponse` | Callers do not depend on HTTP details |
Other design points that affect testing
Keep callouts out of constructors and static initializers
Code that runs a callout when an object is created, or in a static {} block, is hard to control. A test cannot register a mock before the class loads. Put the callout in an explicit method that the test calls after Test.setMock.
Do the callout before the DML
Apex throws a CalloutException ("You have uncommitted work pending") if you make a callout after DML in the same transaction and before it commits. Production code should make its callouts first, then write records. Later chapters show how Test.startTest and Test.stopTest interact with this rule. For now, design the method so the callout step is separate from the save step. That way you can reorder them or move the save to a later job.
Do not put secrets in the code
Hard-coded API keys end up in version control and in test output. Use a Named Credential, so the platform adds authentication and the code holds only the callout: endpoint. Mocks work with these endpoints too. The mock receives the request and sees the callout:Name URL.
Return data, not responses
getCondition returns a String. Callers and their tests do not need to know about status codes or JSON. If the API returns several fields, define a small class, for example WeatherResult, and have the service fill it. Tests of the calling code can then be written against that class.
Do not over-abstract
You could add a HttpClient interface with a send method, and inject a fake in tests. That is a valid choice when you need to test code in a package that must run with no callout setup. It costs extra classes, though, and Test.setMock already provides the same control. Add your own interface only when you have a concrete reason, such as swapping between two providers at runtime.
What comes next
You now have code with one narrow seam for the mock. Next you will implement HttpCalloutMock to return a controlled HttpResponse, and register it with Test.setMock. Then you will write the first end-to-end test against getCondition.
Exercise
A teammate's method builds a request, calls Http.send, and parses the JSON, all in one 40-line method. You want to test the "status is 503" branch and the "invalid JSON" branch without a mock. What two changes do you make to the code, and why does each test then need no Test.setMock call?
Show answer
Move the status check and JSON parsing into a separate method (for example parseCondition) that takes an HttpResponse and returns a value or throws a typed exception. Mark it @TestVisible private, or make it package-visible. Move request building into its own method too, leaving one small method that contains Http.send. The tests for 503 and invalid JSON then create an HttpResponse by hand with setStatusCode and setBody and pass it to the parsing method. That method never calls Http.send, so no callout happens and no mock is needed.