Sub topic 1
Why Apex tests cannot make real callouts
Prerequisites
This chapter assumes you can:
- Read and write basic Apex classes and methods.
- Write and run test classes with
@IsTest. - Recognize HTTP methods, status codes, and JSON.
The rule
A callout is a request from Apex to a system outside Salesforce, such as a REST API. Apex test methods are not allowed to make them. If a test reaches code that sends an HTTP request, the platform stops it and throws a System.CalloutException:
System.CalloutException: Methods defined as TestMethod do not support Web service calloutsThis is not a bug in your code. The platform enforces it for every test, so you must deal with it for every piece of code that makes callouts.
Why the platform enforces it
Tests are supposed to be fast, repeatable, and free of side effects. A real callout breaks all three.
- Repeatability: The remote service can be down, slow, or return different data each run. A test that passes on Monday could fail on Tuesday with no code change.
- Side effects: A POST or DELETE in a test would change data in a real system. Apex rolls back database changes after a test, but it cannot roll back a call to someone else's server.
- Coverage on deploy: Production deployments run your tests. A deployment must not depend on a third-party service being reachable at that moment.
- Credentials and limits: Real callouts need working endpoints, authentication, and remote site settings. Tests should not consume the remote system's rate limits.
The fix is to replace the callout with a fake response that you control. Salesforce calls this a mock. The next chapters build the pieces. Here you only need to see the problem.
The problem in code
This service makes one GET callout and reads the JSON body. It is the code under test throughout this tutorial.
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 line new Http().send(req) is where the callout happens. Now write a test that calls the service with no mock:
@IsTest
private class WeatherServiceNoMockTest {
@IsTest
static void failsWithoutMock() {
Test.startTest();
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a CalloutException');
} catch (CalloutException e) {
Assert.isTrue(
e.getMessage().contains('do not support Web service callouts'),
'The platform should block the real callout'
);
}
Test.stopTest();
}
}This test passes, but only because it expects the failure. It proves the rule and tests nothing about WeatherService. You never reach the status check or the JSON parsing. A test that cannot get past send leaves the most important lines of the class uncovered.
What a test needs instead
Your test must intercept the call at send and hand back a response you chose. That gives you control over the status code and body, so you can exercise every branch of the code.
Your production code stays the same. Only the test registers a mock, so Http.send returns the fake response instead of going to the network.
The pieces you will build over the next chapters are:
- A class that implements
HttpCalloutMockand returns anHttpResponse. - A call to
Test.setMockthat registers it before the callout runs. - Assertions on the result.
Exercise
A teammate says, "We can skip mocking because the test org points at a sandbox API." Give two reasons this still does not work in Apex tests.
Show answer
First, the platform blocks every callout from a test method and throws a CalloutException, whatever the endpoint is. Second, even if it were allowed, a sandbox API can be down or return changing data, so the tests would not be repeatable.