Sub topic 8
Checking the request your code sends
This chapter assumes you can write Apex test classes with @IsTest. It also assumes you have already built a mock with HttpCalloutMock and registered it with Test.setMock, as in the earlier chapters. You should know what an HTTP method, a header, and a JSON body are.
So far your tests have checked what happens after the response arrives. That covers only half of the contract. If WeatherService sends the wrong method, a malformed URL, or a missing header, the real API will reject the call. A test that returns a canned 200 response will still pass. This chapter shows how to make the mock record the outgoing request so the test can inspect it.
Why response-only tests miss bugs
A mock like WeatherServiceMock ignores the request it receives. It returns the same response whatever your code sent. The test then proves that your parsing works, but nothing about the request.
Consider these bugs. Each one passes a response-only test:
- The code sends
POSTinstead ofGET. - The city is not URL-encoded, so
New Yorkbreaks the query string. - The
Acceptheader is misspelled or left out. - A JSON body contains a wrong field name.
- The code makes two callouts where one was intended.
To catch them, the test needs to see the HttpRequest object that reached the mock.
How the test gets the request
The mock's respond method receives the HttpRequest as its argument. Test.setMock stores a reference to the mock instance you pass. Because it is a reference, the test can keep its own variable pointing at the same object. After the code under test runs, the test reads whatever the mock saved.
A recording mock
This mock returns a fixed response, like WeatherServiceMock. It also keeps every request in a public list.
@IsTest
public class RecordingMock implements HttpCalloutMock {
public List<HttpRequest> requests = new List<HttpRequest>();
private Integer statusCode;
private String body;
public RecordingMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
requests.add(req);
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}The RoutingMock from the previous chapter already does the same thing. It has a public requests list and adds each request to it. Everything below works with either class.
Asserting on the method, endpoint, and headers
The test keeps a variable for the mock, registers it, runs the code, and then inspects mock.requests.
@IsTest
private class WeatherServiceRequestTest {
@IsTest
static void sendsExpectedRequest() {
RecordingMock mock = new RecordingMock(200, '{"condition":"Sunny"}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
WeatherService.getCondition('New York');
Test.stopTest();
Assert.areEqual(1, mock.requests.size(), 'Exactly one callout expected');
HttpRequest req = mock.requests[0];
Assert.areEqual('GET', req.getMethod(), 'Weather lookups use GET');
Assert.areEqual(
'https://api.example.com/weather?city=New+York',
req.getEndpoint(),
'The city should be URL-encoded'
);
Assert.areEqual('application/json', req.getHeader('Accept'));
}
}Three details matter here.
- Check the count first.
mock.requests[0]throws aListExceptionif the list is empty. An assertion onsize()gives a clear failure message instead. It also catches code that makes extra calls. - Assert the full endpoint.
EncodingUtil.urlEncodeturns the space inNew Yorkinto+. Comparing the whole string verifies the query string in one assertion. Parsing the URL apart in the test is rarely worth the effort. - Use
getHeaderfor headers you set. It returnsnullfor a header the code never set. A wrong or missing header therefore shows up as an assertion failure with a clear expected value.
Asserting on a request body
For POST and PUT calls, the body is the most important part of the request. Here is a small service that sends a JSON body:
public with sharing class WeatherReportService {
public static void submit(String city, String condition) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/reports');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'city' => city,
'condition' => condition
}));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 201) {
throw new WeatherService.WeatherException('Unexpected status: ' + res.getStatusCode());
}
}
}The test parses the captured body back into a map and compares the fields. It does not compare raw JSON strings.
@IsTest
private class WeatherReportServiceTest {
@IsTest
static void postsReportAsJson() {
RecordingMock mock = new RecordingMock(201, '{}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
WeatherReportService.submit('Oslo', 'Rain');
Test.stopTest();
Assert.areEqual(1, mock.requests.size());
HttpRequest req = mock.requests[0];
Assert.areEqual('POST', req.getMethod());
Assert.areEqual('application/json', req.getHeader('Content-Type'));
Map<String, Object> sent = (Map<String, Object>) JSON.deserializeUntyped(req.getBody());
Assert.areEqual('Oslo', sent.get('city'));
Assert.areEqual('Rain', sent.get('condition'));
}
}Comparing parsed values is more stable than comparing strings. JSON.serialize on a map does not guarantee a particular key order. A string comparison could fail after a harmless refactor, and a parsed comparison would not.
If your code uses setBodyAsBlob, read the body back with req.getBodyAsBlob(). Call the getter that matches the setter. In my experience getBody() returns null for a request whose body was set as a blob, so check this against your API version.
Verifying several requests
When one test triggers more than one callout, use a routing mock and assert on the list in order.
@IsTest
static void sendsTwoRequestsInOrder() {
RoutingMock mock = new RoutingMock();
mock.add('GET', 'https://api.example.com/weather?city=Oslo', 200, '{"condition":"Sunny"}');
mock.add('POST', 'https://api.example.com/reports', 201, '{}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
WeatherReportService.submit('Oslo', condition);
Test.stopTest();
Assert.areEqual(2, mock.requests.size());
Assert.areEqual('GET', mock.requests[0].getMethod());
Assert.areEqual('POST', mock.requests[1].getMethod());
}Assert the order only when it matters to the behavior. If the order is incidental, search the list instead of indexing into it. Tests that pin an incidental order break when someone reorders independent calls.
Do not assert inside respond
You can call Assert.areEqual directly inside respond. It looks convenient, but it has a flaw. A failed assertion throws an AssertException from within Http.send. If the code under test wraps the callout in catch (Exception e), the failure can be swallowed. The test may then pass, or fail with an unrelated message.
There is one more reason to assert after the fact. A test that never reaches the mock will never run the assertion inside it. With a recorded list, Assert.areEqual(1, mock.requests.size()) fails loudly when no callout happened.
What a request check does not prove
The recorded request is the one your code built. Nothing was sent over the network. Two limits follow from that.
- The test shows that your code builds the request you expect. It does not show that the real API accepts it. Keep the expected values in the test copied from the API documentation, not from your own implementation, or the test only repeats the code.
- Authentication through a Named Credential happens when the platform sends the request. The mock sees the endpoint as your code set it, for example
callout:Weather/weather. It will not contain a resolved host or an auth header added by the platform. Assert on what your code controls.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Passing `new RecordingMock(...)` straight into `Test.setMock` | The test has no variable to read afterwards | Assign the mock to a local variable first |
| Indexing `requests[0]` without a size check | `ListException` instead of a useful failure | Assert `size()` first |
| Comparing serialized JSON strings | Failures after key order changes | Parse with `JSON.deserializeUntyped` and compare fields |
| Asserting inside `respond` | Failures swallowed by `catch (Exception e)` | Record, then assert in the test |
| Reading the list before `Test.stopTest()` in async code | Empty list | Read after `stopTest`, which runs the async job |
Exercise
Exercise
A test registers RecordingMock and calls WeatherService.getCondition('Oslo'). It then runs Assert.areEqual('GET', mock.requests[0].getMethod()). The test fails with a ListException. What does this tell you, and how would you change the test so the failure message is more useful?
Show answer
The list is empty, so the mock's respond method was never called and the code under test made no callout. This could mean the callout was skipped, the mock was registered after the callout ran, or the test never reached the code. Add Assert.areEqual(1, mock.requests.size(), 'Expected one callout') before indexing into the list. The failure then states that no callout happened, instead of throwing an unrelated exception.
Exercise
Why is it safer to parse req.getBody() with JSON.deserializeUntyped and compare fields than to compare it with the string '{"city":"Oslo","condition":"Rain"}'?
Show answer
The key order in serialized JSON is not guaranteed, and whitespace can differ. A string comparison can fail after a harmless change even though the body means the same thing. Comparing parsed fields tests the meaning of the body, not its formatting.