0

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:

@RestResource(urlMapping='/xyz/*')
global with sharing class resManager {
@HttpPost
global static void updateRec(myResponse res) {
//Response is placed directly in to the response class
try {
  myObject__c obj = [
    SELECT
      Id, Info__c
    FROM myObject
    WHERE req_Id__c = :res.requestId
    LIMIT 1
  ];

  obj.Info__c = res.info;
  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(
    JSON.serialize(e.getMessage())
   );
  }
}
global class myResponse {
   global string requestId;
   global string info;
  }
}

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

@IsTest
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(
      jsonInput,
      resManager.myResponse.class
    );
    System.assertEquals(result.requestId, 'ayo_z2IdJUBL418Sn7d4b');

    resManager.updateRec(result);
}

Where and how do I initialise the RestContext?

1 Answer 1

3

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;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .