Sub topic 8
Checking the request your code sends
What you will check and why
So far the mock has controlled what your code receives. This chapter covers the other direction: what your code sends. A callout can return the right result and still send a wrong request, such as a missing header, an unencoded parameter, or the wrong HTTP method. The mock returns a canned response whatever it receives, so a test that only checks the return value will not catch these mistakes.
This chapter assumes you can write a basic HttpCalloutMock and register it with Test.setMock, as in the earlier chapters.
How the mock sees the request
Apex calls respond(HttpRequest req) on your mock each time the code under test calls Http.send. The req argument is the exact request your code built. If the mock saves it, the test can inspect it afterwards.
The RoutingMock class from the routing chapter already does this. Its respond method runs requests.add(req) and the list is public.
A request-verification test
WeatherService URL-encodes the city name and sets an Accept header. This test checks both.
@IsTest
private class WeatherServiceRequestTest {
@IsTest
static void sendsEncodedGetRequest() {
String endpoint = 'https://api.example.com/weather?city=New+York';
RoutingMock mock = new RoutingMock();
mock.add('GET', endpoint, 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 sent = mock.requests[0];
Assert.areEqual('GET', sent.getMethod(), 'Method');
Assert.areEqual(endpoint, sent.getEndpoint(), 'The space must be encoded as +');
Assert.areEqual('application/json', sent.getHeader('Accept'), 'Accept header');
}
}The test follows three steps:
- Register the endpoint you expect the code to call.
- Run the code.
- Assert on the recorded request.
Counting the requests catches accidental duplicate calls or a callout that never happened.
What you can read from a request
| Method on `HttpRequest` | Use it to check |
|---|---|
| `getMethod()` | GET, POST, PUT, and so on |
| `getEndpoint()` | URL, including the query string |
| `getHeader('Name')` | A single header value |
| `getBody()` | Body as a string |
| `getBodyAsBlob()` | Body as a Blob, for binary payloads |
For a POST with a JSON body, avoid comparing the whole string. Field order and spacing can change without changing meaning. Parse it instead:
Map<String, Object> payload =
(Map<String, Object>) JSON.deserializeUntyped(sent.getBody());
Assert.areEqual('Oslo', payload.get('city'), 'Body should carry the city');Two behaviors to know
The routing mock matches on method plus endpoint. If your code sends a different endpoint than the one you registered, the mock returns 404. A service that throws on non-200 responses then fails the test with an exception before your assertions run. When you see a WeatherException mentioning 404, compare the registered endpoint with the one your code builds.
Exercise
Exercise
Why does the test in this chapter check mock.requests.size() before reading mock.requests[0], and what does getEndpoint() return if your code forgot to call EncodingUtil.urlEncode for the city "New York"?
Show answer
Checking the size confirms exactly one callout occurred. If none happened, requests[0] would throw a list index error instead of a clear assertion failure, and extra calls would go unnoticed. Without encoding, getEndpoint() would return https://api.example.com/weather?city=New York with a literal space, so the equality assertion fails. Because the mock is registered for the encoded URL, the call also gets a 404 response.