Sub topic 10
Mocking with static resources
This chapter assumes you can write Apex test classes with @IsTest, that you have already written a custom HttpCalloutMock (such as WeatherServiceMock), and that you know how to create a static resource in Salesforce. It builds on the first callout test from the earlier chapters.
Why move response bodies out of Apex
A custom mock like WeatherServiceMock takes the body as a string. That works for {"condition":"Sunny"}. Real API responses are often hundreds of lines of JSON. Pasting them into Apex causes three problems:
- Quotes must be escaped or wrapped in single-quoted strings, which makes the JSON hard to read and easy to break.
- Long literals bury the test logic under data.
- Apex has limits on source size, so very large literals can make a class hard to compile or maintain.
A static resource is a file stored in your org, such as a text file, JSON file, or zip archive. Salesforce provides mock classes that read a static resource and return its contents as the response body. This lets you keep the JSON in a file and leave only the test logic in Apex.
StaticResourceCalloutMock
StaticResourceCalloutMock is a built-in class that implements HttpCalloutMock. You configure it with the name of a static resource, a status code, and optional headers. When the code under test makes a callout, the mock returns the resource contents as the body.
Create a static resource named WeatherResponse containing this JSON. Set its MIME type to application/json.
{
"city": "Oslo",
"condition": "Sunny",
"temperatureC": 21
}Then use the mock in a test:
@IsTest
private static void usesStaticResource() {
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('WeatherResponse');
mock.setStatusCode(200);
mock.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
Assert.isNotNull(condition);
}The method must sit inside a test class. The four configuration calls do the following:
| Method | Purpose |
|---|---|
| `setStaticResource(String name)` | Names the static resource whose contents become the body. |
| `setStatusCode(Integer code)` | Sets the HTTP status code of the response. |
| `setHeader(String name, String value)` | Adds a response header. Call it once per header. |
| `Test.setMock(HttpCalloutMock.class, mock)` | Registers the mock for the rest of the test. |
The test above only checks that the result is not null. Because you control the file, you can assert the exact value. Since the file contains "condition": "Sunny", a stronger check is:
Assert.areEqual('Sunny', condition, 'The condition should come from the static resource');Where the resource must exist
The static resource must exist in the org where the test runs. If the name is wrong or the resource has not been deployed, the test fails when the callout happens, not when you call setStaticResource. Keep the resource in source control with your Apex classes so that deployments carry both together. In a Salesforce DX project, a resource is stored under force-app/main/default/staticresources/ as a file plus a .resource-meta.xml file that declares its content type.
<?xml version="1.0" encoding="UTF-8"?>
<StaticResource xmlns="http://soap.sforce.com/2006/04/metadata">
<cacheControl>Private</cacheControl>
<contentType>application/json</contentType>
</StaticResource>Save this as WeatherResponse.resource-meta.xml next to WeatherResponse.json.
How the call flows
The request never leaves Salesforce. The platform intercepts Http.send and hands control to the registered mock.
Testing error responses with a static resource
The status code is set separately from the body, so one resource can serve more than one test. You can also keep a dedicated error body in another file, such as WeatherError:
@IsTest
private static void throwsOnServerErrorFromResource() {
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('WeatherError');
mock.setStatusCode(500);
mock.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, mock);
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();
}This mirrors the 500 test from the earlier chapter. Only the source of the body changes.
MultiStaticResourceCalloutMock
When one test triggers several callouts to different endpoints, a single resource is not enough. MultiStaticResourceCalloutMock maps endpoint URLs to static resources. It is the static resource counterpart of the routing mock you wrote earlier.
@IsTest
private static void usesMultipleResources() {
MultiStaticResourceCalloutMock multi = new MultiStaticResourceCalloutMock();
multi.setStaticResource('https://api.example.com/weather?city=Oslo', 'WeatherResponse');
multi.setStaticResource('https://api.example.com/weather?city=Bergen', 'WeatherBergen');
multi.setStatusCode(200);
multi.setHeader('Content-Type', 'application/json');
Test.setMock(HttpCalloutMock.class, multi);
Test.startTest();
String oslo = WeatherService.getCondition('Oslo');
String bergen = WeatherService.getCondition('Bergen');
Test.stopTest();
Assert.areEqual('Sunny', oslo, 'Oslo should come from WeatherResponse');
Assert.areEqual('Rain', bergen, 'Bergen should come from WeatherBergen');
}This assumes WeatherBergen holds {"condition":"Rain"}. Points to know about this class:
- The first argument to
setStaticResourceis the full endpoint, including the query string. It must match what the code builds.WeatherServiceURL-encodes the city, soOsloandBergenappear unchanged, but a city likeNew Yorkwould becomeNew+Yorkin the endpoint. - The status code and headers apply to every response. You cannot return a 200 for one endpoint and a 404 for another with this class.
- A request to an endpoint you did not register fails the test with a callout error. If you need a 404 fallback, status codes per route, or request recording, write a routing mock like
RoutingMock.
Choosing between mock types
| Need | Best choice |
|---|---|
| Small body, status codes vary by test | Custom mock such as `WeatherServiceMock` |
| Large or reusable JSON body | `StaticResourceCalloutMock` |
| Several endpoints, same status for all | `MultiStaticResourceCalloutMock` |
| Different status per endpoint, or request inspection | Custom routing mock such as `RoutingMock` |
StaticResourceCalloutMock cannot inspect the request. It returns the same response whatever the method, headers, or body. If you must check what your code sent, use a custom mock that records the request.
Common errors
- The static resource name does not match. Names are case-insensitive but must be otherwise exact. A typo shows up as a failure during the callout.
- The resource is missing from the target org. It works in your scratch org and fails in CI because the resource was not committed or deployed.
- The body is not valid for the parser. A trailing comma or a byte order mark at the start of the file makes
JSON.deserializeUntypedthrow. Validate the file with a JSON tool. - The mock is registered after the callout.
Test.setMockmust run before the code makes its callout. - Missing Content-Type header. Code that checks the response header can fail even when the body is fine.
Summary
Static resource mocks move large response bodies out of Apex and into files you can edit and review as data. StaticResourceCalloutMock returns one resource for every callout. MultiStaticResourceCalloutMock returns a resource per endpoint, with a shared status code and headers. Neither one inspects the request, so reach for a custom mock when you need that or per-route status codes.
Exercise
A test makes two callouts. The first to https://api.example.com/weather?city=Oslo must return 200 with the body from WeatherResponse. The second to https://api.example.com/weather?city=Atlantis must return 404. Can MultiStaticResourceCalloutMock do this, and if not, what should you use?
Show answer
No. MultiStaticResourceCalloutMock applies a single status code and one set of headers to all registered endpoints, so it cannot return 200 for one route and 404 for another. Use a custom routing mock such as RoutingMock: add the Oslo route with status 200 and the JSON body, and leave Atlantis unregistered so the mock returns its default 404 response.
Exercise
Your test calls mock.setStaticResource('WeatherResponse') and Test.setMock(...), but fails with an error when WeatherService.getCondition runs. List two likely causes related to the static resource.
Show answer
The static resource named WeatherResponse may not exist in the org where the test runs (not deployed or not committed), or its name may be misspelled. Another cause is that the file contents are not valid JSON, which makes JSON.deserializeUntyped throw during parsing.