Sub topic 12
Testing Timeouts and Errors
This chapter assumes you can write Apex test classes with @IsTest, that you have read the earlier chapters on CalloutException, status codes, and the RetryableCallout Queueable, and that you know a test cannot make a real HTTP callout. The goal is to prove that each failure path behaves as designed, without calling a real endpoint.
Why failure paths need their own tests
Success-path tests are easy to write, and they give high code coverage. They tell you nothing about what happens when the remote service is slow or returns 503. Failure handling is code that runs rarely in production, usually during an incident, so a bug in it is hard to notice.
A callout test should cover these cases:
- A thrown
CalloutException, which stands in for a timeout or connection failure. - A non-retryable response such as 400 or 404, which must not be retried.
- A retryable response such as 429 or 503, which must schedule another attempt.
- An exhausted retry budget, which must stop.
- A sequence of failure followed by success.
How callout mocks work
Apex blocks real callouts in test context. If a test reaches Http.send without a mock registered, Apex throws a CalloutException with a message like "You have uncommitted work pending" or "Methods defined as TestMethod do not support Web service callouts". You register a mock with Test.setMock(HttpCalloutMock.class, instance). From then on, every Http.send in that test calls your mock's respond method instead of the network.
The mock is just a class, so it can do two things:
- Return an
HttpResponsewith whatever status code, headers, and body you choose. - Throw an exception, which surfaces from
Http.sendexactly as a real network failure would.
Reusable mocks
Writing a new mock class for every test gets repetitive. Put the common ones in one @IsTest class.
@IsTest
public class HttpMocks {
// Throws CalloutException, as Http.send does on a timeout.
public class TimeoutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Read timed out');
}
}
// Always returns the same status code and body.
public class StatusMock implements HttpCalloutMock {
private final Integer statusCode;
private final String body;
public StatusMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setHeader('Content-Type', 'application/json');
res.setBody(body);
return res;
}
}
// Returns queued responses in order. The last one repeats.
public class SequenceMock implements HttpCalloutMock {
private final List<HttpResponse> responses;
public Integer calls = 0;
public SequenceMock(List<HttpResponse> responses) {
this.responses = responses;
}
public HttpResponse respond(HttpRequest req) {
Integer index = Math.min(calls, responses.size() - 1);
calls++;
return responses[index];
}
}
public static HttpResponse response(Integer statusCode, String body) {
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}The respond method receives the HttpRequest, so a mock can also assert on what your code sent, such as the endpoint, method, or an idempotency header. Use Assert.areEqual inside respond for that. A failed assertion in a mock fails the test.
Simulating a timeout
A real timeout is a System.CalloutException thrown from Http.send. Your code never sees a status code. The test in the topic spine already covers the basic case. A fuller version also checks that the original exception is kept as the cause, so the stack trace is not lost.
@IsTest
private class OrderApiClientTimeoutTest {
@IsTest
static void timeoutIsWrappedAndCauseIsKept() {
Test.setMock(HttpCalloutMock.class, new HttpMocks.TimeoutMock());
OrderApiClient.ApiException thrown;
Test.startTest();
try {
OrderApiClient.send('/orders');
} catch (OrderApiClient.ApiException e) {
thrown = e;
}
Test.stopTest();
Assert.isNotNull(thrown, 'Expected an ApiException for the timeout');
Assert.isTrue(thrown.getMessage().contains('Callout failed'));
Assert.isInstanceOfType(thrown.getCause(), System.CalloutException.class);
}
}The test cannot measure the 30-second timeout, and it does not try to. It proves that the code handles the exception. The timeout value itself is a configuration choice you check in code review, or by reading the HttpRequest inside a mock.
Simulating error responses
An HTTP 503 does not throw. Http.send returns normally, and your code must inspect the status. A test that only uses TimeoutMock would miss a bug where the code treats every returned response as success.
@IsTest
private class OrderApiClientStatusTest {
@IsTest
static void errorStatusIsReturnedNotThrown() {
Test.setMock(HttpCalloutMock.class,
new HttpMocks.StatusMock(503, '{"error":"unavailable"}'));
Test.startTest();
HttpResponse res = OrderApiClient.send('/orders');
Test.stopTest();
Assert.areEqual(503, res.getStatusCode());
Assert.isFalse(OrderApiClient.isSuccess(res.getStatusCode()));
Assert.isTrue(OrderApiClient.isRetryable(res.getStatusCode()));
Assert.isTrue(res.getBody().contains('unavailable'));
}
}This test assumes you placed isSuccess and isRetryable in OrderApiClient. Because those methods are pure functions of an integer, test their boundaries directly.
@IsTest
private class StatusClassificationTest {
@IsTest
static void classifiesStatusCodes() {
Set<Integer> retryable = new Set<Integer>{408, 429, 500, 502, 503, 504, 599};
Set<Integer> permanent = new Set<Integer>{400, 401, 403, 404, 409, 422};
for (Integer code : retryable) {
Assert.isTrue(OrderApiClient.isRetryable(code), 'Expected retryable: ' + code);
}
for (Integer code : permanent) {
Assert.isFalse(OrderApiClient.isRetryable(code), 'Expected permanent: ' + code);
}
Assert.isTrue(OrderApiClient.isSuccess(200));
Assert.isTrue(OrderApiClient.isSuccess(299));
Assert.isFalse(OrderApiClient.isSuccess(300));
Assert.isFalse(OrderApiClient.isSuccess(199));
}
}The boundary values (199, 299, 300, 599, 600) catch off-by-one mistakes in the range checks.
Testing the Queueable retry decision
RetryableCallout has three outcomes: finish, retry, or give up. You can test the decision without running the retry chain. Call execute(null) directly and use Limits.getQueueableJobs() to see whether the job enqueued a follow-up. The count is for the current transaction, so it tells you whether System.enqueueJob was called.
@IsTest
private class RetryableCalloutTest {
private static Integer followUpJobs(HttpCalloutMock mock, Integer attempt) {
Test.setMock(HttpCalloutMock.class, mock);
new RetryableCallout('{"orderId":"A-1"}', attempt).execute(null);
return Limits.getQueueableJobs();
}
@IsTest
static void successDoesNotRetry() {
Assert.areEqual(0, followUpJobs(new HttpMocks.StatusMock(201, '{}'), 1));
}
@IsTest
static void serverErrorSchedulesRetry() {
Assert.areEqual(1, followUpJobs(new HttpMocks.StatusMock(503, '{}'), 1));
}
@IsTest
static void rateLimitSchedulesRetry() {
Assert.areEqual(1, followUpJobs(new HttpMocks.StatusMock(429, '{}'), 2));
}
@IsTest
static void timeoutSchedulesRetry() {
Assert.areEqual(1, followUpJobs(new HttpMocks.TimeoutMock(), 1));
}
@IsTest
static void clientErrorDoesNotRetry() {
Assert.areEqual(0, followUpJobs(new HttpMocks.StatusMock(400, '{}'), 1));
}
@IsTest
static void lastAttemptDoesNotRetry() {
// MAX_ATTEMPTS is 4, so attempt 4 must give up.
Assert.areEqual(0, followUpJobs(new HttpMocks.StatusMock(503, '{}'), 4));
}
}The test never calls Test.stopTest(), so the delayed job it enqueues is never executed. This is deliberate. Salesforce limits Queueable chaining inside tests, and letting a chain run can raise a System.AsyncException about stack depth. One attempt per test keeps the result predictable.
The lastAttemptDoesNotRetry test is the most valuable one here. Without it, a mistake such as attempt > MAX_ATTEMPTS instead of >= would let the job make five calls and nothing would fail.
Testing fail-then-succeed
Some behavior spans several calls: a first call fails, a later call succeeds, and the caller never sees an error. If retries run in a loop inside one transaction, SequenceMock tests that directly and lets you assert how many calls were made.
@IsTest
private class SequenceTest {
@IsTest
static void secondCallSucceeds() {
HttpMocks.SequenceMock mock = new HttpMocks.SequenceMock(new List<HttpResponse>{
HttpMocks.response(503, '{"error":"unavailable"}'),
HttpMocks.response(200, '{"id":"A-1"}')
});
Test.setMock(HttpCalloutMock.class, mock);
HttpResponse first = OrderApiClient.send('/orders');
HttpResponse second = OrderApiClient.send('/orders');
Assert.areEqual(503, first.getStatusCode());
Assert.areEqual(200, second.getStatusCode());
Assert.areEqual(2, mock.calls);
}
}With the Queueable design, each attempt is a separate transaction, so a sequence across attempts is not something one unit test can run end to end. Test each attempt on its own, as in the previous section.
Common errors in failure tests
| Symptom | Likely cause | Fix |
|---|---|---|
| "Methods defined as TestMethod do not support Web service callouts" | No mock registered before the callout | Call `Test.setMock` first, in the same test method |
| "You have uncommitted work pending" | DML ran in the test before the callout | Create data in a `@TestSetup` method, or make the callout before the DML |
| `System.AsyncException` about stack depth | A test let a Queueable chain run | Call `execute(null)` once and assert with `Limits.getQueueableJobs()` |
| Test passes but the retry code is not covered | The mock always returns 200 | Add a mock that returns 503 and one that throws |
| `NullPointerException` in the mock | `respond` returned an `HttpResponse` with no status code set | Call `setStatusCode`, or use `HttpMocks.response` |
What tests cannot prove
A mock is only as accurate as your guess about the remote service. These things stay outside what the tests prove:
- The real timeout duration, and whether 30 seconds suits the endpoint.
- Whether the remote service really returns 429 with a
Retry-Afterheader, or a different code. - Whether the remote service honors the idempotency key.
- The real delay between retries. The tests check that a job is enqueued, not when it runs.
Check these in a sandbox against the real or a staging endpoint, and write down the responses you observe. Then copy those real status codes and bodies into your mocks, so the tests reflect what the service actually sends.
Exercise
A teammate writes RetryableCallout so that a 404 is treated as retryable. Which test from this chapter fails first, and what single new test would you add to catch a similar mistake for 401?
Show answer
clientErrorDoesNotRetry fails first, because it feeds a 400 and expects zero follow-up jobs. If the whole 4xx range became retryable, StatusClassificationTest also fails on the permanent set, which includes 404. To cover 401, add a test such as unauthorizedDoesNotRetry that calls followUpJobs(new HttpMocks.StatusMock(401, '{}'), 1) and asserts the result is 0. Add 401 to the permanent set in StatusClassificationTest as well.
Exercise
Why does the RetryableCalloutTest class avoid calling Test.stopTest(), and what would you lose if you used SequenceMock there instead of calling execute(null) once per test?
Show answer
Calling Test.stopTest() runs the enqueued follow-up job, which can chain further and raise a stack-depth AsyncException in test context. Not calling it keeps each test to one attempt. A SequenceMock would suggest that several attempts run in one test. In production each attempt is a separate transaction, so the test would not match real behavior, and the chaining limit in tests would stop it anyway. You would lose the clear link between one input outcome and one retry decision.