Sub topic 1
Why Apex tests cannot make real callouts
Apex code often calls an outside service over HTTP. This chapter explains why Apex tests are not allowed to make those calls. It also shows the error you get when a test tries, and what the platform expects you to do instead.
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic Apex classes, methods, and exceptions.
- Write and run a test class with
@IsTest,Test.startTest(), andTest.stopTest(). - Read an HTTP request and response: methods such as GET and POST, status codes such as 200 and 500, and JSON bodies.
You do not need to know anything about mocks yet. That is the subject of the following chapters.
What a callout is
A callout is a request that Apex sends to a system outside Salesforce. Examples are a REST API call with Http.send() or a SOAP call through a generated web service class. The code runs inside Salesforce, but the response comes from another server.
Here is the class that this tutorial tests. It makes one GET request and reads one field from the JSON response.
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 the callout. Everything else in the method is ordinary Apex: building the request, checking the status code, and parsing JSON. All of that logic is worth testing, but the callout line sits in the middle of it.
What happens when a test makes a real callout
Write the most natural test and run it.
@IsTest
private class WeatherServiceNoMockTest {
@IsTest
static void failsWithoutMock() {
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
Assert.areEqual('Sunny', condition);
}
}The test fails before it reaches the assertion. The platform throws this exception at the send call:
System.CalloutException: Methods defined as TestMethod do not support Web service calloutsThis is not a configuration problem. Adding the endpoint to Remote Site Settings, creating a Named Credential, or opening a firewall does not change it. During a test run, Http.send() never contacts the network unless a mock has been registered. Without a registered mock, it throws.
The same rule covers other kinds of callouts. SOAP calls through generated classes and other web service callouts are blocked in tests in the same way. Each kind has its own mock interface. This tutorial focuses on the HTTP one.
Why the platform enforces this
The restriction looks like an obstacle, but each reason behind it describes a property you also want from your own tests.
- Tests must be repeatable. A real service can be slow, down, rate limited, or return different data each time. A test that depends on it fails for reasons unrelated to your code.
- Tests must be isolated. Apex tests roll back their database changes when they finish. A callout cannot be rolled back. If the endpoint creates a record, sends a message, or charges a card, every test run would repeat that side effect against a real system.
- Tests must be able to run anywhere. Deployments run tests in sandboxes, scratch orgs, and production. Those environments often have different credentials, different allowed endpoints, or no access to the service at all.
- Tests must be fast. Salesforce runs many tests in parallel and sets time limits on them. Network round trips make a suite slow and flaky.
- Tests must be able to cause failures. To check how your code handles a 500 response or a malformed body, you need to produce that response on demand. A real service rarely does that when you ask.
The consequence is that you test your code against a stand-in for the service, not against the service. You still run the full request-building and response-handling logic. You only replace the network hop.
How the platform lets a test continue
Salesforce lets a test tell the runtime, "when this code makes a callout, give it this response." That response comes from an object you write, called a mock, and you register it with Test.setMock. After that, Http.send() stops contacting the network. It hands the HttpRequest to your mock and returns the HttpResponse the mock gives back.
Here is a short preview of the fix. The next chapters explain each piece, so for now only note the order of the steps. The mock is registered first, and the callout code runs after that.
@IsTest
private class WeatherServiceFirstLookTest {
@IsTest
static void worksWithMock() {
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');
}
}WeatherServiceMock is a class you write once and reuse. The test never contacts api.example.com. The code under test is unchanged and does not know it received a fake response.
Common mistakes around the restriction
Skipping the callout in test context
Some developers add a guard to production code so it does nothing during tests.
// Anti-pattern: do not do this
if (!Test.isRunningTest()) {
res = new Http().send(req);
}This makes the test pass, but it also removes the code you meant to test. The status check and the JSON parsing no longer run. The tests then report coverage for lines they never exercised properly. A mock keeps all of the code live, so prefer a mock.
Registering the mock too late
Test.setMock only affects callouts made after it runs. If the callout happens first, for example in test setup code, it throws the same CalloutException. Register the mock at the top of the test method, before anything that might call out.
Mixing up the two callout errors
Two errors look related, but they have different causes:
| Error message | Cause | Fix |
|---|---|---|
| `Methods defined as TestMethod do not support Web service callouts` | A callout ran and no mock was registered. | Call `Test.setMock` before the callout. |
| `You have uncommitted work pending. Please commit or rollback before calling out` | DML ran earlier in the same transaction and the callout came after it. | Reorder the work, or use `Test.startTest()`. A later chapter covers this. |
Expecting production setup to matter
Remote Site Settings and Named Credentials are needed when code calls a real endpoint at runtime. A test that uses a mock never reaches that check. A test passing therefore tells you nothing about whether the production endpoint is configured. Verify that part separately, in the org where the code will run.
What a mock test does and does not prove
A mocked test shows that your code builds a sensible request, handles each kind of response correctly, and parses the body correctly. It does not show that the real service behaves the way your mock claims. If the service changes its response format, your tests keep passing because the mock still returns the old format. Keep mock bodies close to real sample responses from the API documentation, and refresh them when the contract changes.
Summary
- A callout is an HTTP or SOAP request from Apex to an outside system.
- In a test,
Http.send()throwsSystem.CalloutExceptionunless a mock is registered. - The rule exists because tests need to be repeatable, isolated, fast, and able to produce failures on demand.
- A mock replaces the network hop, not your code, so request building and response handling still run.
- Avoid
Test.isRunningTest()guards that skip callouts. They remove the logic you want to test.
Exercise
A developer's test calls WeatherService.getCondition('Oslo') and fails with "Methods defined as TestMethod do not support Web service callouts". They add api.example.com to Remote Site Settings, and the test still fails. Why, and what should they do instead?
Show answer
Remote Site Settings only control real callouts at runtime. In a test, Http.send() throws unless a mock has been registered, whatever the settings say. The developer should write a class that implements HttpCalloutMock, and call Test.setMock(HttpCalloutMock.class, new YourMock(...)) at the start of the test, before the callout runs.
Exercise
A teammate wraps the callout in if (!Test.isRunningTest()) so the tests pass. Give two reasons this is a poor fix.
Show answer
First, the status check and the JSON parsing no longer run in the test, so the logic you meant to test is skipped. Second, coverage numbers can look fine while the tests do not check the behavior. A registered mock keeps every line live and lets you control the response for both success and error cases.