Sub topic 3
Writing callout code that is easy to test
This chapter assumes you can write Apex classes and @IsTest methods, and that you know how Http, HttpRequest, and HttpResponse work. The mock itself comes in the next chapter. Here you shape the production code so the mock is easy to apply and most of the logic needs no mock.
Why design matters
A test cannot send a real callout, so every test that reaches Http.send needs a mock. Suppose a method builds the request, sends it, checks the status, and parses the body. Then every test of any of those steps must set up a mock. Splitting the method into small steps lets you test most of the logic directly.
Separate building, sending, and parsing
Here is WeatherService refactored into three steps. The behavior is the same as before.
public with sharing class WeatherService {
public class WeatherException extends Exception {}
public static String getCondition(String city) {
HttpResponse res = new Http().send(buildRequest(city));
return parseCondition(res);
}
@TestVisible
private static HttpRequest buildRequest(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');
return req;
}
@TestVisible
private static String parseCondition(HttpResponse res) {
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');
}
}@TestVisible lets a test call a private method without making it public API. Only getCondition calls send. The other two methods take plain values and return plain values.
Test the pure steps without a mock
You can build an HttpResponse by hand in a test and pass it to parseCondition. No callout happens, so no mock is needed.
@IsTest
private class WeatherServiceParsingTest {
@IsTest
static void parsesConditionFromBody() {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"condition":"Snow"}');
Assert.areEqual('Snow', WeatherService.parseCondition(res));
}
@IsTest
static void buildsEncodedRequest() {
HttpRequest req = WeatherService.buildRequest('New York');
Assert.areEqual('GET', req.getMethod());
Assert.isTrue(req.getEndpoint().endsWith('city=New+York'), 'City should be URL-encoded');
}
}These tests run fast and fail for one reason each. You still need at least one full test through getCondition with a mock. You will write it in a later chapter.
Other habits that help
- Keep the callout out of constructors and static initializers. A callout there runs whenever the class loads, and every test that touches the class then needs a mock.
- Throw a typed exception for failures.
WeatherExceptionlets a test catch exactly the failure it expects, instead of a genericException. - Return data, not side effects. A method that returns a
Stringis easier to assert on than one that writes to a field or a log. - Keep the endpoint in one place. A Named Credential endpoint such as
callout:Weather_API/weatherkeeps credentials and hostnames out of the code. The mock ignores the endpoint, so this does not change your tests. - Keep callouts away from uncommitted DML. Apex throws a
CalloutExceptionif you make a callout after DML in the same transaction without committing. Do the callout first, or move it to asynchronous Apex. A later chapter covers this.
Exercise
A method builds a request, sends it, and parses the response, all in one block. Name two refactorings that make it easier to test, and say which parts then need no mock.
Show answer
Move request construction into a separate method (for example buildRequest), and move response checking and parsing into another (for example parseCondition). Mark both @TestVisible. Only the method that calls Http.send needs a mock. The build and parse methods can be tested directly, with a hand-built HttpResponse for the parse method.