Sub topic 10
Writing Tests for REST Handlers
This chapter assumes you can write Apex tests with @IsTest and Assert, and that you have the AccountRestService class from the earlier chapters. You will test its handlers without any HTTP call.
How the test works
An Apex REST handler is a static method that reads its input from RestContext.request and writes its output to RestContext.response. Both are static properties you can assign. A test builds a RestRequest and a RestResponse, assigns them to RestContext, and calls the method like any other static method.
No callout happens, so there is nothing to mock. The Salesforce routing layer (URL matching, authentication, JSON binding) is skipped. You are testing your logic, not the platform.
Testing a GET handler
The GET handler takes the record Id from the last segment of requestURI. The test must set that URI, or the handler queries with the wrong value. It must also set RestContext.response, because the handler writes res.statusCode and would throw a NullPointerException on a null response.
@IsTest
private class AccountRestServiceTest {
private static void setUpRequest(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');
insert a;
setUpRequest('/services/apexrest/v1/Accounts/' + a.Id, 'GET');
Account result = AccountRestService.getAccount();
Assert.areEqual(a.Id, result.Id);
Assert.areEqual(Null, RestContext.response.statusCode == 0 ? null : null);
}
}That last assertion is meaningless, so remove it. On success the handler never sets a status code, so the response keeps its default. Assert on the status code only in the error tests below.
Testing the error paths
Each status code your handler can return needs its own test. For the 404, delete the record first so the Id is valid but no longer exists.
@IsTest
static void getAccountReturns404WhenMissing() {
Account a = new Account(Name = 'Temporary');
insert a;
delete a;
setUpRequest('/services/apexrest/v1/Accounts/' + a.Id, 'GET');
Account result = AccountRestService.getAccount();
Assert.isNull(result);
Assert.areEqual(404, RestContext.response.statusCode);
}Add these two tests to the same test class. The POST handler binds name and industry from the JSON body at runtime. In a test you pass them as ordinary arguments. A null name makes the insert fail with a required-field error, which exercises the 400 branch.
@IsTest
static void createAccountReturns201() {
setUpRequest('/services/apexrest/v1/Accounts/', 'POST');
CreateResult result = AccountRestService.createAccount('Acme', 'Banking');
Assert.areEqual(201, RestContext.response.statusCode);
Assert.isTrue(result.success);
Assert.areEqual('Acme', [SELECT Name FROM Account WHERE Id = :result.id].Name);
}
@IsTest
static void createAccountReturns400OnDmlError() {
setUpRequest('/services/apexrest/v1/Accounts/', 'POST');
CreateResult result = AccountRestService.createAccount(null, 'Banking');
Assert.areEqual(400, RestContext.response.statusCode);
Assert.isFalse(result.success);
Assert.isNotNull(result.message);
}Handlers that read the body directly
If a handler reads RestContext.request.requestBody itself, set the body as a Blob in the test:
req.requestBody = Blob.valueOf('{"name":"Acme","industry":"Banking"}');Set headers and query parameters the same way, with req.addHeader('Content-Type', 'application/json') and req.addParameter('limit', '10').
Common errors
- NullPointerException on
RestContext.response. The test did not assign aRestResponse. - Wrong record found.
requestURIdoes not end with the Id. The handler usessubstringAfterLast('/'), so a trailing slash returns an empty string. - Passing tests that prove nothing. You asserted on the return value but not on
statusCode. Clients depend on the status code. - Security never tested. Tests run in system context by default, so sharing and field-level security checks always pass.
Exercise
A test calls AccountRestService.getAccount() and fails with a NullPointerException on the line res.statusCode = 404. The test sets RestContext.request correctly. What is missing, and why does the handler fail only on that line?
Show answer
The test never assigned RestContext.response = new RestResponse(). The handler reads RestContext.response into res at the start, so res is null. Nothing dereferences it until the not-found branch runs and sets statusCode. A test that finds a record would pass by accident.