Sub topic 2
Registering the Mock with Test.setMock
Assume you know basic Apex classes, @IsTest methods, HTTP status codes, and JSON. The examples use a WeatherService class whose getCondition method sends one HTTP GET request.
Registering a Mock
Apex tests cannot call an external service. A mock is a test object that implements HttpCalloutMock and returns a controlled HttpResponse.
Register the mock before the code under test runs:
Test.setMock(
HttpCalloutMock.class,
new WeatherServiceMock(200, '{"condition":"Sunny"}')
);Test.setMock tells the test runtime which object should answer HTTP requests. The callout code still uses Http.send; the runtime sends that request to the mock instead.
Your First Callout Test
This test checks the successful response path. Test.startTest and Test.stopTest mark the code whose limits and asynchronous work the test should measure.
@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'
);
}
}The assertion checks the returned value instead of only checking that no exception occurred. That proves the service parsed the response correctly.
Testing Errors and Failures
A useful test also covers non-success status codes. Configure the mock with a server-error response and assert the exception that WeatherService is expected to throw.
@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'));
}
Test.stopTest();
}Checking the Outgoing Request
A mock can store the received HttpRequest. After the service runs, assert the method, endpoint, or headers. This catches encoding and configuration mistakes that response assertions cannot detect.
@IsTest
static void sendsExpectedRequest() {
WeatherServiceMock mock =
new WeatherServiceMock(200, '{"condition":"Sunny"}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
WeatherService.getCondition('New York');
Test.stopTest();
Assert.areEqual(1, mock.requests.size());
Assert.areEqual('GET', mock.requests[0].getMethod());
Assert.isTrue(mock.requests[0].getEndpoint().contains('New%20York'));
}Your mock must expose a requests list and add each request inside respond.
Exercise
What happens if the test calls WeatherService.getCondition before Test.setMock?
Show answer
The callout has no registered response, so the test fails instead of receiving the configured fake response.