Sub topic 9
Routing several callouts in one test
This chapter assumes you can write an HttpCalloutMock, register it with Test.setMock, and write a basic callout test, as covered in the earlier chapters. You should also be comfortable with Map and List in Apex.
Why one fixed response is not enough
WeatherServiceMock returns the same status code and body for every request. That works when the code under test makes one callout. Real code often makes several in one transaction:
- It fetches a list, then fetches details for each item.
- It authenticates, then calls the business endpoint with the token.
- It sends a
POST, then reads the result with aGET.
Test.setMock registers one mock per type, so a second call to Test.setMock(HttpCalloutMock.class, ...) replaces the first. You cannot register one mock per endpoint. Instead, you register a single mock whose respond method looks at the incoming request and decides what to return.
Code under test
The examples in this chapter use a class that calls WeatherService once per city. Each call is a separate callout to a different URL.
public with sharing class WeatherSummary {
public static Map<String, String> forCities(List<String> cities) {
Map<String, String> result = new Map<String, String>();
for (String city : cities) {
result.put(city, WeatherService.getCondition(city));
}
return result;
}
}For Oslo, WeatherService sends GET https://api.example.com/weather?city=Oslo. For Bergen, the endpoint ends in city=Bergen. A routing mock must tell these two apart.
The routing mock
RoutingMock keeps a map from a route key to a canned HttpResponse. The key is the HTTP method, a space, and the endpoint. It also records every request it receives.
@IsTest
public class RoutingMock implements HttpCalloutMock {
private Map<String, HttpResponse> responses = new Map<String, HttpResponse>();
public List<HttpRequest> requests = new List<HttpRequest>();
public void add(String method, String endpoint, Integer statusCode, String body) {
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setBody(body);
responses.put(method + ' ' + endpoint, res);
}
public HttpResponse respond(HttpRequest req) {
requests.add(req);
HttpResponse res = responses.get(req.getMethod() + ' ' + req.getEndpoint());
if (res == null) {
res = new HttpResponse();
res.setStatusCode(404);
res.setBody('No mock registered');
}
return res;
}
}Three design choices matter here.
- The route key combines method and endpoint. A
GETand aPOSTto the same URL get different responses. - Unregistered calls return 404. If your code calls a URL you did not expect, the test sees a 404 and fails visibly. It does not silently receive a success body.
- Requests are recorded. The mock is a spy as well as a stub, so the test can check what was sent after the fact.
The add method is not part of the HttpCalloutMock interface. It exists so the test can configure the mock before registering it.
Writing the test
Create the mock, add one route per expected callout, register it, then run the code.
@IsTest
private class WeatherSummaryTest {
@IsTest
static void returnsConditionForEachCity() {
RoutingMock mock = new RoutingMock();
mock.add('GET', 'https://api.example.com/weather?city=Oslo', 200, '{"condition":"Sunny"}');
mock.add('GET', 'https://api.example.com/weather?city=Bergen', 200, '{"condition":"Rain"}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
Map<String, String> result = WeatherSummary.forCities(new List<String>{ 'Oslo', 'Bergen' });
Test.stopTest();
Assert.areEqual(2, result.size(), 'Both cities should be in the result');
Assert.areEqual('Sunny', result.get('Oslo'), 'Oslo should get the Oslo body');
Assert.areEqual('Rain', result.get('Bergen'), 'Bergen should get the Bergen body');
Assert.areEqual(2, mock.requests.size(), 'Exactly two callouts should be made');
}
}Keep a reference to mock in a local variable. Test.setMock takes the instance, so the object you inspect after Test.stopTest() is the same object that handled the callouts.
The assertion on result.get('Oslo') proves that routing worked. If the mock returned the same body for both cities, the test would fail on one of the two lines.
Routing a failure for one of several calls
Routing is also the easiest way to test partial failure. Register a success for one route and an error for another.
@IsTest
static void failsWhenSecondCityReturnsServerError() {
RoutingMock mock = new RoutingMock();
mock.add('GET', 'https://api.example.com/weather?city=Oslo', 200, '{"condition":"Sunny"}');
mock.add('GET', 'https://api.example.com/weather?city=Bergen', 500, '{"error":"boom"}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
try {
WeatherSummary.forCities(new List<String>{ 'Oslo', 'Bergen' });
Assert.fail('Expected a WeatherException for Bergen');
} catch (WeatherService.WeatherException e) {
Assert.isTrue(e.getMessage().contains('500'), 'Message should include the status code');
}
Test.stopTest();
Assert.areEqual(2, mock.requests.size(), 'Oslo succeeded and Bergen failed, so both were attempted');
}The last assertion documents behavior: the loop stops at the first exception, but both callouts happened before it did. If you later change forCities to collect errors instead of throwing, this test tells you what changed.
Using the recorded requests
Because RoutingMock stores each HttpRequest, you can check order and content, not only the count.
Assert.areEqual('Oslo', mock.requests[0].getEndpoint().substringAfter('city='), 'Oslo is requested first');
Assert.areEqual('Bergen', mock.requests[1].getEndpoint().substringAfter('city='), 'Bergen is requested second');
Assert.areEqual('application/json', mock.requests[0].getHeader('Accept'), 'Accept header is set');Only assert on order when order is part of the contract. If the code iterates over a Set, the order is not guaranteed, and an order assertion makes the test brittle. Prefer asserting on the count and on the set of endpoints that were called.
Matching strategies
Exact string matching is the simplest approach, and it has a cost. Any change to the endpoint, such as a different query parameter order or a new parameter, breaks the key and produces a 404.
| Strategy | Key | Good for | Risk |
|---|---|---|---|
| Exact match | Method plus full endpoint | Fixed URLs, query strings you control | Brittle when URLs change |
| Path match | Method plus the endpoint without the query string | Many calls to one path with different parameters | Cannot return different bodies per parameter |
| Contains match | Method plus a fragment of the URL | Endpoints with generated IDs | A loose fragment can match the wrong route |
To switch to path matching, strip the query string in both add and respond:
private static String routeKey(String method, String endpoint) {
return method + ' ' + endpoint.substringBefore('?');
}Use routeKey when storing and when looking up. If you need different bodies per parameter, as in the Oslo and Bergen example, keep the query string in the key.
Common pitfalls
- Registering the mock after the callout.
Test.setMockmust run before any code that sends the request. Call it beforeTest.startTest()or at the start of the test. - Calling
Test.setMocktwice. The second call replaces the first. Add all routes to one mock, then register it once. - Assuming a missing route fails the test. The mock returns a 404 response. If your code treats 404 as an expected case, such as "not found", the test may pass for the wrong reason. Assert on the response data and on
mock.requests, and not only on "no exception". - Sharing one
HttpResponseacross calls. The map stores one response object per key and returns that same instance each time. That is fine for read-only use. If the code under test modifies the response, build a newHttpResponseinsiderespondinstead. - Hitting callout limits. A transaction can make at most 100 callouts. A test that loops over more than 100 items will hit that limit even with a mock.
- Forgetting the DML rule. If the test inserts records and then runs callout code, you must perform the DML before
Test.startTest(), as covered in the chapter on DML and callout ordering. Otherwise Apex raises an uncommitted work pending error.
When to use something else
A routing mock is the right tool when the callouts differ by URL or method. If every callout in the test should return the same thing, WeatherServiceMock is simpler. If the bodies are large JSON documents, store them as static resources and use MultiStaticResourceCalloutMock, which routes by endpoint without custom Apex. The next chapter covers that.
Exercise
A test registers a RoutingMock with a route for POST https://api.example.com/orders. The code under test sends POST https://api.example.com/orders?dryRun=true. The test fails with a "No mock registered" message from the response body. Why does this happen, and what are two ways to fix it?
Show answer
The route key is the method plus the full endpoint, and the actual endpoint includes ?dryRun=true, so the lookup finds no match and the mock returns its default 404 response. Fix it by registering the route with the exact endpoint including ?dryRun=true, or by changing the mock to build its key from endpoint.substringBefore('?') in both add and respond, so all calls to that path share one route.
Exercise
Your test calls Test.setMock(HttpCalloutMock.class, mockA) for an authentication call and then Test.setMock(HttpCalloutMock.class, mockB) for a data call, then runs code that makes both callouts. What goes wrong, and how do you fix the test?
Show answer
The second Test.setMock call replaces the first, so only mockB answers, and the authentication callout gets whatever mockB returns for it (or an error). Fix it by creating one RoutingMock, adding a route for the authentication endpoint and a route for the data endpoint, and calling Test.setMock once with that mock.