Sub topic 6
Your first callout test
This chapter assumes you can write Apex classes and @IsTest methods, and that you know HTTP methods, status codes, and JSON. You will test the WeatherService class from earlier chapters with a mock. By the end you will have a passing success test and an error test, and you will know why each line is there.
What you are testing
WeatherService.getCondition builds a GET request, sends it, checks the status code, and reads the condition field from the JSON body.
public with sharing class WeatherService {
public class WeatherException extends Exception {}
public static String getCondition(String city) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.example.com/weather?city=' + EncodingUtil.urlEncode(city, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new WeatherException('Unexpected status: ' + res.getStatusCode());
}
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('condition');
}
}The method has two paths that matter: a 200 response that yields a string, and any other status that throws. A complete test suite covers both. In this chapter you write one test for each.
The mock
Apex tests cannot send real HTTP requests. If a test reaches Http.send with no mock registered, the platform throws a System.CalloutException with the message "Methods defined as TestMethod do not support Web service callouts". The mock stands in for the remote server.
A mock is a class that implements HttpCalloutMock. The interface has one method, respond(HttpRequest), which receives the request your code built and returns the HttpResponse your code will see.
This mock takes a status code and a body in its constructor, so one class serves many tests.
@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;
}
}The @IsTest annotation on the class keeps it out of your org's code size limit and prevents production code from calling it.
How the pieces connect
Your test registers the mock with Test.setMock. When the code under test calls Http.send, the platform does not open a network connection. It calls respond on the registered mock and returns that response.
Two details follow from this flow:
- The mock must be registered before the callout runs. Registering it afterwards has no effect on a call that already happened.
- The mock sees the real
HttpRequestyour code built. That is what lets you assert on the request, which a later chapter covers.
The test class
Here are both tests together.
@IsTest
private class WeatherServiceTest {
@IsTest
static void returnsConditionOnSuccess() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Sunny"}'));
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
Assert.areEqual('Sunny', condition, 'The condition should come from the mocked body');
}
@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 success test, step by step
- Arrange.
Test.setMock(HttpCalloutMock.class, ...)registers a mock that answers 200 with{"condition":"Sunny"}. The first argument is the interface type. The second is your instance. - Act.
Test.startTest()andTest.stopTest()bracket the call. Inside them,getCondition('Oslo')runs, reachesHttp.send, and receives the mock's response. - Assert.
Assert.areEqualcompares the expected string with the actual one. The third argument is a message that appears if the assertion fails.
The assertion proves the whole chain: the request was sent, the status check passed, the JSON was parsed, and the right field was returned.
The error test, step by step
The second test registers a 500 response. The code under test should throw WeatherException, so the test has two jobs. It must fail if no exception is thrown, and it must check the exception's content.
Assert.failruns only ifgetConditionreturns normally. It turns a missing exception into a test failure.- The
catchblock handles the expected exception type. The assertion inside confirms the message contains500.
There is a subtle trap here. Assert.fail throws its own exception. That exception is not a WeatherException, so the catch block does not swallow it, and the test fails as intended. If you caught a general Exception instead, the catch would swallow the failure from Assert.fail and the test would pass when it should not. Always catch the most specific type.
Why `Test.startTest` and `Test.stopTest` are here
For a plain synchronous callout, the pair is optional. The mock works without them. They are included for three reasons:
- They give the code under test a fresh set of governor limits, separate from any setup work in the test.
- They mark clearly which line is the action being tested.
- They become required once the code under test runs asynchronously, such as a Queueable job.
Test.stopTestis what forces that job to finish.
Keep setup that is not under test, such as creating records, before Test.startTest. A later chapter covers the DML ordering rule in detail.
Reading failures
When a callout test fails, the cause is usually one of these.
| Symptom | Likely cause | Fix |
|---|---|---|
| `CalloutException`: "Methods defined as TestMethod do not support Web service callouts" | No mock registered, or registered after the callout | Call `Test.setMock` before the code that sends the request |
| `TypeException` or `NullPointerException` while parsing | The mock body is not the JSON shape the code expects | Print the body and compare it with what the parser reads |
| Success test fails with "Unexpected status" | The mock was constructed with a non-200 code | Check the constructor arguments |
| Error test passes but should not | A broad `catch (Exception e)` swallowed `Assert.fail` | Catch the specific exception type |
A useful habit is to break the code on purpose. Change the expected value to 'Rainy' and confirm the test fails with your message. A test you have never seen fail is a test you cannot fully trust.
A third test to try
The code reads body.get('condition'). If the API returns {}, the method returns null rather than throwing. You can pin that behavior down with a test.
@IsTest
static void returnsNullWhenConditionMissing() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{}'));
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
Assert.isNull(condition, 'A missing field should produce null');
}Add it to WeatherServiceTest. Whether null is the behavior you want is a design question. The test records what the code does today, so any later change is deliberate.
Exercise
In the error test, why is Assert.fail('Expected a WeatherException') placed right after the call to getCondition, and what goes wrong if the catch block catches Exception instead of WeatherService.WeatherException?
Show answer
Assert.fail runs only when getCondition returns without throwing, so it turns a missing exception into a failed test. If the catch block caught Exception, it would also catch the failure thrown by Assert.fail. The test would then pass even though the expected WeatherException was never raised.
Exercise
A teammate registers the mock with Test.setMock on the line after WeatherService.getCondition('Oslo'). What happens, and why?
Show answer
The test throws a CalloutException at the getCondition call. The callout runs before any mock is registered, and the platform does not allow real callouts in tests. A mock only affects callouts made after Test.setMock runs.