Sub topic 7
Testing error responses and failures
This chapter assumes you can write Apex test classes with @IsTest, you know HTTP status codes, and you have already written a first callout test with Test.setMock. The code under test is WeatherService.getCondition, which throws a WeatherException for any status other than 200.
Why error paths need their own tests
A callout that works on the happy path can still fail in production. The remote server may return a 404, a 500, or a body that is not valid JSON. If you only test the 200 case, the error branches in your code run for the first time in production.
A mock makes these failures easy to reproduce. You choose the status code and body, and the code under test reacts as if the server had sent them.
Reuse one mock for every status code
WeatherServiceMock takes the status code and body in its constructor. You don't need a new mock class for each scenario. You only change the arguments.
@IsTest
public class WeatherServiceMock implements HttpCalloutMock {
private Integer statusCode;
private String body;
public WeatherServiceMock(Integer statusCode, String body) {
this.statusCode = statusCode;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setStatusCode(statusCode);
res.setBody(body);
return res;
}
}Test that a 500 raises an exception
The service throws WeatherService.WeatherException when the status is not 200. The test below registers a 500 response and expects that exception.
@IsTest
private class WeatherServiceTest {
@IsTest
static void throwsOnServerError() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(500, '{"error":"boom"}'));
Test.startTest();
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a WeatherException');
} catch (WeatherService.WeatherException e) {
Assert.isTrue(e.getMessage().contains('500'), 'Message should include the status code');
}
Test.stopTest();
}
}The pattern has three parts:
- Register the mock before the callout runs.
- Call the code inside a
tryblock, and callAssert.failright after it. If no exception is thrown, the test fails with a clear message. - Catch the specific exception type and assert on its message.
Why Assert.fail needs care
Assert.fail throws an AssertException. That exception is not a WeatherException, so your catch block does not swallow it. This is why catching the specific type matters. If you caught the generic Exception, the failure signal would be caught and the test would pass when it should not.
// Risky: catches the AssertException thrown by Assert.fail
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a WeatherException');
} catch (Exception e) {
// The test passes even if no WeatherException was thrown
}The failure flow
The diagram shows what happens when the mock returns a 500.
Other failures worth covering
Status codes are only one source of errors. Consider these cases too:
| Scenario | Mock setup | What to assert |
|---|---|---|
| Not found | `new WeatherServiceMock(404, '{}')` | `WeatherException` with `404` in the message |
| Malformed JSON | `new WeatherServiceMock(200, 'not json')` | A `JSONException` is thrown |
| Empty body | `new WeatherServiceMock(200, '{}')` | The returned condition is `null` |
The malformed JSON case is a good example of a bug the happy path hides. JSON.deserializeUntyped throws on invalid input, and the current service does not handle it. A test documents that behavior, and you can later decide whether to wrap it in a WeatherException.
@IsTest
static void throwsOnMalformedJson() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, 'not json'));
Test.startTest();
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a JSONException');
} catch (JSONException e) {
Assert.isNotNull(e.getMessage(), 'The exception should carry a message');
}
Test.stopTest();
}Simulating a network failure
A real network failure raises a CalloutException, and the mock never returns a response. To test it, make respond throw instead of returning.
@IsTest
public class FailingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Simulated timeout');
}
}Register it with Test.setMock(HttpCalloutMock.class, new FailingMock()) and expect CalloutException from the service.
Exercise
Why should the catch block in an error-path test name a specific exception type instead of Exception?
Show answer
Assert.fail throws an AssertException, which is itself an Exception. A generic catch would swallow it, and the test would pass even when the code under test never threw. Catching the specific type, such as WeatherService.WeatherException, lets the assertion failure propagate.
Exercise
Write the line that registers a mock that makes the service see a 404 response with an empty JSON object as the body.
Show answer
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(404, '{}'));