Create a test class for RestResource class with a response code

Salesforce Asked by Irene on December 10, 2020

I have a @RestResource class which receives data from a third party, finds the matching record and updates it, then returns a success/fail to the third party. I’ve just added the RestContext.response to return a 200 or 400 code, which was successful (for both a 200 and a 400 test) when I tested using Postman. However when I run the test class it fails with a null pointer exception.

I’ve done some research and have figured out it’s because the RestContext is not initialised in my test class, but am not sure how to do this correctly. When I tried to initialise it, my ‘real’ test from Postman keeps return 200, even when it shouldn’t, and the message part is blank, so I’m obviously doing something incorrectly (I’ve removed it from my code sample now)

My very simplified apex class:

global with sharing class resManager {
global static void updateRec(myResponse res) {
//Response is placed directly in to the response class
try {
  myObject__c obj = [
      Id, Info__c
    FROM myObject
    WHERE req_Id__c = :res.requestId
    LIMIT 1

  obj.Info__c =;
  update obj;
  //RestContext.response = new RestResponse();
  RestContext.response.statusCode = 200;
  RestContext.response.responseBody = Blob.valueOf(
    JSON.serialize(' updated successfully')

} catch (Exception e) {
  //RestContext.response = new RestResponse();
   RestContext.response.statusCode = 400;
   RestContext.response.responseBody = Blob.valueOf(
global class myResponse {
   global string requestId;
   global string info;

This is my test class (with which I get a null pointer exception error):

public class resManager_Test {
  public testMethod static void test1() {

    Account acct = TestData.createAccount(null);
    insert acct;

    myObject__c obj = new myObject__c(
      req_Id__c = 'ayo_z2IdJUBL418Sn7d4b',
      Account__c = acct.Id,
      Status__c = 'Awaiting Results'

    insert obj;

    String jsonInput =
      '{"requestId": "ayo_z2IdJUBL418Sn7d4b",' +
      '"info": "The quick brown fox jumps...blha blah"}';
    resManager.myResponse result = (resManager.myResponse) JSON.deserialize(
    System.assertEquals(result.requestId, 'ayo_z2IdJUBL418Sn7d4b');


Where and how do I initialise the RestContext?

One Answer

It appears all I needed to do was add this to the test class at the start of the method (before the Account acct... line):

RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/xyz'; //Request URL
req.httpMethod = 'POST';

RestContext.request = req;
RestContext.response= res;

Correct answer by Irene on December 10, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP