Sub topic 10
Writing tests for REST handlers
This chapter assumes you can write Apex classes and @IsTest methods, and that you know the AccountRestService resource from earlier chapters. It also assumes you know how SOQL, DML and HTTP status codes work. Here you will test REST handlers without making an HTTP call, cover the error paths, and check that security behaves as intended.
Why REST handlers are tested by direct calls
An Apex REST handler is a global static method. Salesforce routes an incoming HTTP request to it and fills in RestContext. In a test, no request arrives, so you play the part of the platform. You build a RestRequest and a RestResponse, assign them to RestContext, and call the method like any other static method.
This has three consequences:
- No callout happens, so you do not need
Test.setMock. - Nothing runs the URL router. A wrong
urlMappingwill not fail your test. The handler only sees therequestURIyou set. - Nothing serializes your return value. The test receives the Apex object, not JSON. To check the JSON shape, serialize the result yourself with
JSON.serialize.
The test setup pattern
Every handler test needs the same setup: a request with a URI and method, and a fresh response. Put it in a helper so each test stays short.
@IsTest
private class AccountRestServiceTest {
private static void setRequest(String uri, String method) {
RestRequest req = new RestRequest();
req.requestURI = uri;
req.httpMethod = method;
RestContext.request = req;
RestContext.response = new RestResponse();
}
@IsTest
static void getAccountReturnsRecord() {
Account a = new Account(Name = 'Test Account', Industry = 'Energy');
insert a;
setRequest('/services/apexrest/v1/Accounts/' + a.Id, 'GET');
Account result = AccountRestService.getAccount();
Assert.areEqual(a.Id, result.Id);
Assert.areEqual('Test Account', result.Name);
Assert.areEqual(200, RestContext.response.statusCode == null ? 200 : RestContext.response.statusCode);
}
}A new RestResponse has a null status code until the handler sets one. The last assertion above accounts for that. A cleaner approach is to assert only on codes that your handler sets explicitly, as the next sections do.
Testing the failure paths
The success path is the easy part. Each branch in the handler needs its own test, because a REST service's contract includes its errors. For getAccount, the branch to cover is the 404 when no record matches.
@IsTest
static void getAccountReturns404WhenMissing() {
// A well-formed Id that matches no Account
Account a = new Account(Name = 'Temp');
insert a;
Id missingId = a.Id;
delete a;
setRequest('/services/apexrest/v1/Accounts/' + missingId, 'GET');
Account result = AccountRestService.getAccount();
Assert.isNull(result);
Assert.areEqual(404, RestContext.response.statusCode);
}Inserting and then deleting a record gives you a valid Id that is guaranteed to match nothing. This is more reliable than inventing an Id string.
Think about other bad inputs too:
- A malformed Id, such as
abc. Binding it to an Id-typed SOQL variable can throw aStringExceptionor return no rows, depending on how the handler is written. Test what your handler actually does, then decide whether that is the behavior you want. - A URI with no Id segment at all.
- A record the running user cannot see (covered later in this chapter).
Testing @HttpPost with bound parameters
When a client sends a JSON body, the platform binds its top-level keys to the method parameters by name. In a test you skip the binding and pass the arguments directly. The following test uses the CreateResult class from the earlier chapter.
@IsTest
static void createAccountReturns201() {
setRequest('/services/apexrest/v1/Accounts/', 'POST');
AccountRestService.CreateResult result =
AccountRestService.createAccount('New Co', 'Energy');
Assert.isTrue(result.success);
Assert.areEqual(201, RestContext.response.statusCode);
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE Id = :result.id]);
}
@IsTest
static void createAccountReturns400OnDmlFailure() {
setRequest('/services/apexrest/v1/Accounts/', 'POST');
// Name is required on Account, so a null name makes the insert fail.
AccountRestService.CreateResult result =
AccountRestService.createAccount(null, 'Energy');
Assert.isFalse(result.success);
Assert.areEqual(400, RestContext.response.statusCode);
Assert.isNotNull(result.message);
}This example assumes CreateResult is declared as an inner class of AccountRestService. If you declared it as a top-level class, drop the AccountRestService. prefix.
The second test is the one that matters most. It proves the catch (DmlException e) block works and that the response code changes from 201 to 400.
Testing handlers that read the body
Some handlers take no bound parameters and read RestContext.request.requestBody themselves, for example when they deserialize into a wrapper class. In a test, set the body as a Blob.
@RestResource(urlMapping='/v1/Contacts/*')
global with sharing class ContactRestService {
global class ContactRequest {
global String lastName;
global String email;
}
@HttpPost
global static void createContact() {
RestResponse res = RestContext.response;
res.addHeader('Content-Type', 'application/json');
try {
ContactRequest body = (ContactRequest) JSON.deserialize(
RestContext.request.requestBody.toString(),
ContactRequest.class
);
Contact c = new Contact(LastName = body.lastName, Email = body.email);
insert as user c;
res.statusCode = 201;
res.responseBody = Blob.valueOf(JSON.serialize(new Map<String, Object>{ 'id' => c.Id }));
} catch (JSONException e) {
res.statusCode = 400;
res.responseBody = Blob.valueOf('{"error":"Invalid JSON"}');
} catch (DmlException e) {
res.statusCode = 400;
res.responseBody = Blob.valueOf(JSON.serialize(new Map<String, Object>{ 'error' => e.getMessage() }));
}
}
}@IsTest
private class ContactRestServiceTest {
private static void post(String body) {
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/v1/Contacts/';
req.httpMethod = 'POST';
req.requestBody = Blob.valueOf(body);
RestContext.request = req;
RestContext.response = new RestResponse();
}
@IsTest
static void validBodyCreatesContact() {
post('{"lastName":"Rivera","email":"[email protected]"}');
ContactRestService.createContact();
Assert.areEqual(201, RestContext.response.statusCode);
Map<String, Object> json = (Map<String, Object>)
JSON.deserializeUntyped(RestContext.response.responseBody.toString());
Assert.isNotNull(json.get('id'));
}
@IsTest
static void malformedJsonReturns400() {
post('{not json');
ContactRestService.createContact();
Assert.areEqual(400, RestContext.response.statusCode);
}
}When the handler is void and writes responseBody, the response is your only output. Read it with RestContext.response.responseBody.toString() and parse it to check the content.
Testing query parameters and headers
Set query parameters with addParameter, and headers with addHeader. Both exist on RestRequest.
RestRequest req = new RestRequest();
req.requestURI = '/services/apexrest/v1/Accounts';
req.httpMethod = 'GET';
req.addParameter('industry', 'Energy');
req.addHeader('X-Client-Version', '2');
RestContext.request = req;
RestContext.response = new RestResponse();A handler then reads these with req.params.get('industry') and req.headers.get('X-Client-Version'). In a real request, the platform builds params from the query string. In a test, only what you add is present, so a typo in the parameter name produces a null that looks like a handler bug.
Testing sharing and field-level security
A test that runs as the default user often passes for the wrong reason. A system administrator can see everything, so WITH USER_MODE and insert as user never fail. To prove your security checks work, use System.runAs with a user whose permissions are limited.
@IsTest
static void userWithoutReadAccessGetsNothing() {
Account a = new Account(Name = 'Hidden');
insert a;
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'lim1',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Limited',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'limited' + System.currentTimeMillis() + '@example.com'
);
insert u;
System.runAs(u) {
setRequest('/services/apexrest/v1/Accounts/' + a.Id, 'GET');
try {
AccountRestService.getAccount();
Assert.fail('Expected a query exception');
} catch (QueryException e) {
Assert.isTrue(e.getMessage().containsIgnoreCase('Account'));
}
}
}The "Minimum Access - Salesforce" profile has no object access, so the user mode query throws a QueryException. This is also a prompt to check the handler. If the exception is not caught, the client gets a 500 instead of a 403. Writing the test often shows that the handler needs a catch block that sets the right status code.
You can also grant specific access with a permission set. Create the PermissionSetAssignment before System.runAs, so your setup does not run under the limited user.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting to set `RestContext.response` | `System.NullPointerException` when the handler sets `statusCode` | Assign `new RestResponse()` in the setup helper |
| Setting `requestURI` without the Id segment | Handler's `substringAfterLast` returns an empty string | Build the URI from the full path plus the Id |
| Asserting `statusCode == 200` on success | Assertion fails because the code is `null` | Assert only on codes the handler sets, or check for `null` |
| Relying on org data | Test passes in one org and fails in another | Create all records in the test |
| Testing only as the admin running the test | Security gaps go unnoticed | Add a `System.runAs` test with a limited user |
| Comparing JSON strings directly | Test breaks when key order changes | Deserialize, then assert on values |
| Testing only the success path | Coverage met, errors untested | One test per branch and status code |
Checking the serialized shape
Because the platform serializes return values, a field you forgot to make global or a property that serializes with an unexpected name will never show up in a direct-call test. If the JSON contract matters, serialize the result in the test.
@IsTest
static void responseJsonContainsExpectedKeys() {
Account a = new Account(Name = 'Shape Co', Industry = 'Energy');
insert a;
setRequest('/services/apexrest/v1/Accounts/' + a.Id, 'GET');
Account result = AccountRestService.getAccount();
Map<String, Object> json = (Map<String, Object>)
JSON.deserializeUntyped(JSON.serialize(result));
Assert.isTrue(json.containsKey('Name'));
Assert.areEqual('Energy', json.get('Industry'));
}This is close to what the platform produces, but it is not identical. For a final check, call the deployed service with a real token, as described in the next chapter.
Exercises
Exercise
Your test calls a handler that sets RestContext.response.statusCode = 404, but it fails with a System.NullPointerException before the assertion. What is the most likely cause, and how do you fix it?
Show answer
The test never assigned RestContext.response, so it is null when the handler tries to set statusCode. Assign RestContext.response = new RestResponse(); in the test setup, ideally in a shared helper that also sets RestContext.request.
Exercise
You wrote a test for an @HttpGet handler that uses WITH USER_MODE. It always passes, even when you remove all field permissions from the profile you are testing. Why, and what should you change?
Show answer
The test method runs as the user who started the test run, typically an administrator with full access, so user mode checks always succeed. Create a user with a restricted profile and run the handler inside System.runAs(thatUser), then assert on the exception or status code the handler produces.
Exercise
A handler declares createContact() with no parameters and reads the body from the request. How do you supply a JSON body in a test, and how do you read the response?
Show answer
Set req.requestBody = Blob.valueOf(jsonString) on the RestRequest before assigning it to RestContext.request. After calling the method, read RestContext.response.responseBody.toString() and parse it with JSON.deserializeUntyped or JSON.deserialize, then assert on the values and on RestContext.response.statusCode.