Sub topic 12
Testing timeouts and errors
This chapter assumes you can write basic Apex tests and know how Test.setMock works with HttpCalloutMock. Apex tests cannot make real callouts. Without a mock, a test that reaches Http.send fails with "Methods defined as TestMethod do not support Web service callouts". A mock gives you something more useful than a workaround. It lets you force failures that are rare and hard to reproduce against a real endpoint.
What you need to simulate
Each of the two failure kinds from earlier chapters needs its own test.
- A thrown exception. A timeout or connection failure surfaces as
System.CalloutException. The mock simulates it by throwing fromrespond. - An error response. A 4xx or 5xx status does not throw. The mock returns an
HttpResponsewith that status code.
Simulating a timeout
The mock below throws a CalloutException, the same type Apex throws when a real request times out. The test checks that OrderApiClient.send wraps it in the domain exception.
@IsTest
private class OrderApiClientTest {
private class TimeoutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Read timed out');
}
}
@IsTest
static void timeoutIsWrappedInApiException() {
Test.setMock(HttpCalloutMock.class, new TimeoutMock());
Boolean caught = false;
Test.startTest();
try {
OrderApiClient.send('/orders');
} catch (OrderApiClient.ApiException e) {
caught = true;
Assert.isTrue(e.getMessage().contains('Callout failed'));
}
Test.stopTest();
Assert.isTrue(caught, 'Expected an ApiException for the timeout');
}
}The caught flag matters. If the code under test never throws, a bare try/catch would let the test pass without checking anything. The final assertion makes the test fail in that case.
Simulating error responses
A single configurable mock covers many status codes. It returns whatever status code you give it.
@IsTest
private 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;
}
}You can now test the classification logic from the earlier chapter without any callout. These tests call isRetryable and isSuccess directly. They assume both methods are public static methods on OrderApiClient.
@IsTest
private class StatusClassificationTest {
@IsTest
static void transientCodesAreRetryable() {
for (Integer code : new List<Integer>{ 408, 429, 500, 503 }) {
Assert.isTrue(OrderApiClient.isRetryable(code), 'Expected retryable: ' + code);
}
}
@IsTest
static void clientErrorsArePermanent() {
for (Integer code : new List<Integer>{ 400, 401, 404, 422 }) {
Assert.isFalse(OrderApiClient.isRetryable(code), 'Expected permanent: ' + code);
}
}
@IsTest
static void serverErrorResponseDoesNotThrow() {
Test.setMock(HttpCalloutMock.class, new StatusMock(503, '{"error":"unavailable"}'));
Test.startTest();
HttpResponse res = OrderApiClient.send('/orders');
Test.stopTest();
Assert.areEqual(503, res.getStatusCode());
Assert.isFalse(OrderApiClient.isSuccess(res.getStatusCode()));
}
}The last test confirms a point from earlier chapters: a 503 comes back as a normal response, not an exception.
Testing the retry job
Queueable jobs run when Test.stopTest() is called. Code that re-enqueues itself needs care here. In a test, a chained job enqueued from a running job does not run again, so you can check only one attempt per test.
You can verify what a failed attempt did by counting the queued jobs afterward.
@IsTest
private class RetryableCalloutTest {
@IsTest
static void retryableStatusSchedulesAnotherAttempt() {
Test.setMock(HttpCalloutMock.class, new StatusMock(503, '{}'));
Test.startTest();
System.enqueueJob(new RetryableCallout('{"id":"A1"}', 1));
Test.stopTest();
Integer jobs = [
SELECT COUNT() FROM AsyncApexJob
WHERE ApexClass.Name = 'RetryableCallout'
];
Assert.isTrue(jobs >= 1, 'The first attempt should have run');
}
}Treat the count as a smoke check. To test the retry limit precisely, construct the job with attempt equal to MAX_ATTEMPTS and confirm that it logs and stops instead of enqueuing again. For that, make the delay and limit logic testable by moving it into a small static method.
Common mistakes
- Calling
Test.setMockafter the callout. The mock must be set before the code runs. - Putting DML before a callout in a test. The same "uncommitted work pending" rule applies. Put setup data before
Test.startTest(), and keep any DML that follows from preceding the callout. - Testing only the happy path. A mock that always returns 200 hides every failure branch.
- Asserting on the log text. Assert on observable results such as the status code, the exception type, or the job count.
Exercise
A test sets a mock that returns status 500 and calls OrderApiClient.send inside a try/catch for ApiException, then asserts nothing else. The test passes even if the client is broken. Why, and what changes the outcome?
Show answer
A 500 response does not throw, so the catch block never runs and nothing is checked. Assert on the returned response, for example that getStatusCode() equals 500 and isRetryable(500) is true. To test the exception path, use a mock that throws CalloutException and assert that the catch block ran by checking a flag after Test.stopTest().