Sub topic 7
Testing error responses and failures
This chapter assumes you can write @IsTest classes, you know how HttpCalloutMock and Test.setMock fit together from the previous chapters, and you know HTTP status codes and JSON. The examples reuse WeatherService, WeatherServiceMock, and the success test from earlier.
Why failure paths need their own tests
A callout test that only covers a 200 response proves the happy path and little else. Production callouts fail in ways you can't control: the remote service returns 5xx, a proxy returns an HTML error page, the connection times out, or the API changes its payload. Your code decides what happens next. It might throw, return a default, or log and retry.
Tests are the only place you can force those situations on demand. A mock lets you produce each failure deterministically, in milliseconds, without a real network.
There are three distinct failure families, and each is simulated differently:
| Failure | How the mock simulates it | Typical exception raised |
|---|---|---|
| Non-success HTTP status | `HttpResponse` with status 4xx or 5xx | Your own exception, such as `WeatherException` |
| Successful status, bad body | Status 200 with invalid or unexpected JSON | `System.JSONException` or `System.TypeException` |
| Transport failure | `respond` throws instead of returning | `System.CalloutException` |
Non-success status codes
The earlier test checked a single 500 response. Real services return many failure codes, and your code should treat them consistently. The existing WeatherServiceMock already accepts any status code, so you can loop over a list of codes in one test method.
@IsTest
private class WeatherServiceErrorTest {
@IsTest
static void rejectsEveryNon200Status() {
List<Integer> codes = new List<Integer>{ 400, 401, 404, 500, 503 };
for (Integer code : codes) {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(code, '{"error":"failure"}'));
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a WeatherException for status ' + code);
} catch (WeatherService.WeatherException e) {
Assert.isTrue(
e.getMessage().contains(String.valueOf(code)),
'Message should include status ' + code + ' but was: ' + e.getMessage()
);
}
}
}
}Calling Test.setMock again replaces the previous mock, so each loop iteration gets its own response. This test does not call Test.startTest, because that method can be called only once per test method. A callout test with no DML before the callout does not need it. The next sections and the DML chapter cover when it matters.
The catch-all trap
The try/catch pattern above has a failure mode. Assert.fail throws an AssertException, which extends Exception. If you write catch (Exception e) instead of catching the specific type, you swallow your own failure signal:
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a WeatherException');
} catch (Exception e) {
// Catches the AssertException too. If nothing is asserted here, the test passes
// even when the service never threw.
}Catch the narrowest exception type you expect. If you must catch Exception, assert on e.getTypeName() or use e instanceof WeatherService.WeatherException inside the catch block.
Valid status, unusable body
A 200 response does not guarantee a parseable body. Gateways, captive portals, and API version changes all produce 200 responses with the wrong content. WeatherService calls JSON.deserializeUntyped and then casts the result to a Map, so there are two ways it can break.
- A body that is not JSON, such as an HTML page, makes
JSON.deserializeUntypedthrowSystem.JSONException. - A JSON array instead of an object parses fine, but the cast to
Map<String, Object>throwsSystem.TypeException.
A third case causes no exception at all. If the object lacks a condition key, body.get('condition') returns null.
@IsTest
static void failsOnNonJsonBody() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '<html>Gateway error</html>'));
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a JSONException');
} catch (JSONException e) {
Assert.isNotNull(e.getMessage(), 'The parser should explain the failure');
}
}
@IsTest
static void failsOnUnexpectedJsonShape() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '["Sunny"]'));
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a TypeException');
} catch (TypeException e) {
Assert.isNotNull(e.getMessage(), 'The failed cast should be reported');
}
}
@IsTest
static void returnsNullWhenFieldIsMissing() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"temperature":12}'));
String condition = WeatherService.getCondition('Oslo');
Assert.isNull(condition, 'A missing field currently yields null');
}The last test documents current behavior rather than ideal behavior. Returning null for a malformed payload pushes the problem onto every caller. A test like this makes the decision visible. If you later change the service to throw a WeatherException for a missing field, this test fails and you update it on purpose.
Transport failures: a mock that throws
A timeout or DNS failure never produces an HttpResponse. In Apex, Http.send throws System.CalloutException instead. You can reproduce this by writing a mock whose respond method throws.
@IsTest
public class CalloutFailureMock implements HttpCalloutMock {
private String message;
public CalloutFailureMock(String message) {
this.message = message;
}
public HttpResponse respond(HttpRequest req) {
throw new CalloutException(message);
}
}The exception propagates out of new Http().send(req) into the code under test, just as a real network error would.
@IsTest
static void propagatesCalloutException() {
Test.setMock(HttpCalloutMock.class, new CalloutFailureMock('Read timed out'));
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a CalloutException');
} catch (CalloutException e) {
Assert.areEqual('Read timed out', e.getMessage(), 'The original message should reach the caller');
}
}WeatherService has no try/catch of its own, so this test confirms that transport errors reach the caller unchanged. If you later add retry or wrapping logic, this is the test to extend. A wrapping version would assert that a WeatherException is thrown and that e.getCause() is the original CalloutException.
Choosing what to assert
For each failure, decide what the caller is promised, and assert that and nothing more.
- Assert the exception type. Callers write
catchblocks against it, so it is part of the contract. - Assert the message only on details you control, such as the status code the service embeds. Avoid matching the full text of system messages like parser errors, because Salesforce can change them between releases.
- Assert side effects. If your code saves a log record or flips a status field on failure, query for it after the call. The error path is often where data gets left in a bad state.
- Give every assertion a message. A failure in a loop like
rejectsEveryNon200Statusis much easier to read when the message includes the status code.
Exercise
A developer writes a test that calls WeatherService.getCondition('Oslo') against a 500 mock. The code is inside try { ...; Assert.fail('Expected an exception'); } catch (Exception e) { } with nothing in the catch block. The service is later changed so it never throws on a 500. Does the test fail? Explain why, and how to fix the test.
Show answer
The test still passes. Assert.fail throws an AssertException, which extends Exception, so the empty catch (Exception e) swallows it and the test ends normally. Fix it by catching the specific exception type, WeatherService.WeatherException, so the AssertException propagates and fails the test. Alternatively, assert on e.getTypeName() or use instanceof inside the catch block.