Sub topic 9
Routing several callouts in one test
This chapter assumes you can write an HttpCalloutMock and register it with Test.setMock. It also assumes you have seen a single-callout test like the ones for WeatherService.
The problem: one mock, many callouts
Test.setMock registers one mock for the whole test. If the code under test makes more than one callout, that single mock's respond method handles every request. A mock that always returns the same body will give the wrong response to at least one of them.
For example, a method might fetch a city's weather and then fetch a forecast for the same city. The two calls go to different endpoints and return different JSON. The fix is to make the mock look at each request and choose a response to match.
A routing mock
RoutingMock keeps a map from a key to a prepared HttpResponse. The key combines the HTTP method and the endpoint. It also records every request it receives, so the test can inspect them afterwards.
@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
addmethod is not part of the interface. The test calls it before registering the mock, to set up the routes. - An unregistered request gets a 404 instead of an exception. The code under test then sees a normal error response, and the failure message tells you which call was unexpected.
- The
requestslist is public, so the test can assert on what was sent.
Using it in a test
The test builds the mock, adds one route per expected callout, registers it, and then runs the code. The endpoint in each route must match exactly what the code sends, including URL encoding. WeatherService builds its URL with EncodingUtil.urlEncode, so the key for Oslo is https://api.example.com/weather?city=Oslo.
@IsTest
private class WeatherRoutingTest {
@IsTest
static void routesByMethodAndEndpoint() {
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();
String oslo = WeatherService.getCondition('Oslo');
String bergen = WeatherService.getCondition('Bergen');
Test.stopTest();
Assert.areEqual('Sunny', oslo, 'Oslo should get the first route');
Assert.areEqual('Rain', bergen, 'Bergen should get the second route');
Assert.areEqual(2, mock.requests.size(), 'Both callouts should be recorded');
Assert.areEqual('GET', mock.requests[0].getMethod(), 'The first call should be a GET');
}
}The routing mock is a class-level object, so the test keeps its own reference to it. After Test.stopTest(), it reads mock.requests to confirm how many calls were made and what they looked like.
Common errors
- Key mismatch. If the endpoint in
adddiffers from the one the code builds, even by a trailing slash or an encoded character, the mock returns 404. Printreq.getEndpoint()when a route is not found. - Query strings. Exact-match keys include the query string. If the order of parameters can change, match on a prefix with
startsWithinstead of a map lookup. - Forgetting the mock reference. If you pass
new RoutingMock()straight intoTest.setMock, you cannot readrequestslater. - Shared state. Each test should create its own
RoutingMock. Reusing one across tests leaks recorded requests.
Exercise
A test registers a RoutingMock with a route for GET https://api.example.com/weather?city=Oslo. The code under test calls the same URL with a POST. What does the code receive, and why?
Show answer
It receives a 404 response with the body "No mock registered". The routing key is the method plus the endpoint, so POST https://api.example.com/weather?city=Oslo does not match the registered GET ... key, and the mock falls back to its 404 response.