Sub topic 5
Registering the mock with Test.setMock
This chapter covers how Test.setMock connects a mock class to the code under test. It assumes you can write Apex classes and @IsTest methods, and that you have already implemented HttpCalloutMock (the previous chapter). You also need to know what an HttpRequest and HttpResponse are.
What Test.setMock does
A mock class does nothing on its own. Apex only uses it when the test tells the runtime to substitute it for the real network call. Test.setMock makes that substitution.
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Sunny"}'));The method takes two arguments:
- The interface type, written as
HttpCalloutMock.class. This tells the runtime which kind of callout to intercept. For HTTP callouts it is alwaysHttpCalloutMock.class. - An instance of your mock, which must implement that interface. Pass an object, not a class name.
After registration, every call to Http.send(req) in the same test context goes to your mock's respond(HttpRequest) method. The request never leaves Salesforce. Whatever HttpResponse you return becomes the return value of send.
When to call it
Call Test.setMock before the first callout runs. The registration is read at the moment Http.send executes, so the order inside the test method matters.
@IsTest
static void returnsConditionOnSuccess() {
// 1. Register the mock
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Sunny"}'));
// 2. Run the code that makes the callout
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
// 3. Assert
Assert.areEqual('Sunny', condition);
}Test.setMock can go before or after Test.startTest(), as long as it comes before the callout. The common convention is to put it first, as in the example above. That keeps setup visible at the top and groups the mock with the other test data.
If a test reaches a callout with no mock registered, the runtime throws a System.CalloutException with the message "Methods defined as TestMethod do not support Web service callouts". This is the most common error in callout tests, and it means the registration is missing or runs too late.
How the runtime dispatches a callout
The sequence below shows what happens when the code under test calls send.
Two points follow from this flow:
- The code under test is unchanged. It builds a normal
HttpRequestand callssend. It does not know a mock is active. - Your mock receives the actual
HttpRequestthe code built. That is why a mock can inspect the endpoint, method, headers, and body, which later chapters use for request verification.
Which interface goes with which callout
Test.setMock accepts more than one interface type. The type you pass must match the kind of callout the code makes.
| Callout type | First argument | Mock must implement |
|---|---|---|
| HTTP (REST) via `Http.send` | `HttpCalloutMock.class` | `HttpCalloutMock` |
| SOAP from WSDL-generated classes | `WebServiceMock.class` | `WebServiceMock` |
If you pass the wrong interface for the callout, the runtime does not use your mock. The callout then fails as if no mock existed. This chapter uses HttpCalloutMock. SOAP is covered in a later chapter.
One mock per test, and replacing it
You can register only one active mock for a given interface at a time. Calling Test.setMock a second time with the same interface replaces the first registration. The runtime does not combine them.
@IsTest
static void secondRegistrationWins() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(500, '{"error":"boom"}'));
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Fog"}'));
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
Assert.areEqual('Fog', condition, 'The latest registration should be used');
}This has two practical consequences:
- If one test method needs different responses for different callouts, a single registration must handle all of them. Use a routing mock that picks a response from the request. The later chapter on routing shows this.
- Replacing a mock partway through a test is legal. You can use it to switch from a failing response to a succeeding one, for example to test a retry. Keep this deliberate, because it is easy to do by accident when helper methods each call
Test.setMock.
Registration is also scoped to the test method. Each @IsTest method starts with no mock, so every test that triggers a callout needs its own Test.setMock call, or a shared helper that makes it.
Sharing setup with a helper
When many tests use the same default response, wrap the registration in a private helper. This keeps each test short and gives you one place to change the default.
@IsTest
private class WeatherServiceHelperTest {
private static void mockWeather(Integer statusCode, String body) {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(statusCode, body));
}
@IsTest
static void returnsSunny() {
mockWeather(200, '{"condition":"Sunny"}');
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
Assert.areEqual('Sunny', condition);
}
@IsTest
static void rejectsServerError() {
mockWeather(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();
}
}Do not call this helper from @TestSetup. A mock registered in @TestSetup does not carry over into the test methods. Register it inside each test method, or inside a helper that each test method calls.
Where the mock applies
The mock applies to callouts made in the same transaction as the test method. It also covers asynchronous work that the test forces to run, such as a Queueable job executed at Test.stopTest(). That is why the Queueable example from the plan sets the mock first and enqueues the job afterward.
@IsTest
static void runsCalloutInQueueable() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Rain"}'));
Test.startTest();
System.enqueueJob(new WeatherSyncJob('Oslo'));
Test.stopTest();
}The mock must be registered before Test.stopTest() runs the job. If you register it afterward, the job has already executed against no mock and failed.
Common errors
| 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 calls `send` |
| Compile error on `Test.setMock` | Passed the class name or a type that does not implement the interface | Pass `HttpCalloutMock.class` and an instance such as `new MyMock()` |
| Mock returns the wrong body | A later `Test.setMock` replaced the earlier one | Search the test and its helpers for repeated registrations |
| Mock is ignored in a SOAP call | Used `HttpCalloutMock.class` for a SOAP callout | Use `WebServiceMock.class` with a `WebServiceMock` implementation |
| Mock works in one test but not another | Registered in `@TestSetup` | Register inside each test method |
Summary of the rules
- Call
Test.setMock(HttpCalloutMock.class, new YourMock())before anyHttp.sendcall. - Pass an instance, and match the interface type to the callout type.
- Registering again with the same interface replaces the earlier mock.
- Register in each test method. Registrations from
@TestSetupdo not carry over. - Register before
Test.stopTest()when asynchronous code makes the callout.
Exercise
A test registers Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Sunny"}')) and then, a few lines later, registers new WeatherServiceMock(500, '{"error":"boom"}') before calling WeatherService.getCondition('Oslo'). What does the call do, and why?
Show answer
It throws a WeatherService.WeatherException with a message containing 500. A second Test.setMock call with the same interface replaces the first registration, so the 500 mock handles the callout and the 200 mock is never used.
Exercise
A test method calls WeatherService.getCondition('Oslo') and fails with "Methods defined as TestMethod do not support Web service callouts". The test class contains a @TestSetup method that calls Test.setMock. What is wrong, and how do you fix it?
Show answer
A mock registered in @TestSetup does not carry over into the test methods, so no mock is active when the callout runs. Move the Test.setMock call into the test method, or into a helper that the test method calls before the callout.