Sub topic 6
Your first callout test
This chapter assumes you can write basic Apex classes, run @IsTest classes, and read HTTP status codes and JSON. Apex blocks real callouts during tests, so every callout test registers a mock first. Here you combine a service class, a mock class, and Test.setMock into one passing test.
The code under test
WeatherService.getCondition makes one GET callout. It throws a WeatherException for any status other than 200. Otherwise it parses the JSON body and returns the condition field.
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');
}
}A reusable mock
The mock implements HttpCalloutMock. Its respond method receives the outgoing HttpRequest and returns the HttpResponse your code will see. This version takes the status code and body in its constructor, so each test decides what the "server" says.
@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 test
A callout test has three steps: register the mock, run the code, assert on the result.
@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();
}
}Walk through the success test:
Test.setMock(HttpCalloutMock.class, ...)tells the platform which mock answers callouts in this test. It must run before the callout.Test.startTest()andTest.stopTest()wrap the code under test. They give it a fresh set of governor limits.getConditionbuilds the request and callssend. The platform routes that call torespondon your mock instead of the network.Assert.areEqualchecks that the value parsed from the fake body came back.
The second test shows the failure path. Assert.fail inside the try block makes the test fail if no exception is thrown. The catch is specific to WeatherException, so a different exception type will not pass by accident.
Common errors
- "Methods defined as TestMethod do not support Web service callouts": the test reached
sendwithout a registered mock. CallTest.setMockbefore the code that makes the callout. - Mock set after the callout: the order matters. Registering the mock on a later line has no effect on earlier callouts.
- Wrong body shape: if the mocked JSON lacks the
conditionkey,body.get('condition')returnsnull. The test then fails on the assertion, not in the mock. - Unreadable assertion failures: always pass a message as the last argument to
Assertmethods.
Exercise
In returnsConditionOnSuccess, what happens if you move the Test.setMock line to after the WeatherService.getCondition('Oslo') call?
Show answer
The callout runs before any mock is registered, so the platform rejects it with an error that test methods do not support web service callouts. The mock must be registered before the code that calls Http.send.