[SalesForce] RestContext.response returns null when run in Test Context

Why RestContext.response returns null when called in Test Context. Directly invoking the service do not returns null. Any workaround to execute the test without breaking the code is welcome. Its required to return a status code in the response.

@RestResource(urlMapping='/results/*') 
global with sharing class TestService{

@HttpGet 
global static void doGet() {
        RestRequest req = RestContext.request;
                RestResponse res = RestContext.response;

                // set the status code and response body for test case
                res.statusCode = 200; // Get a null pointer exception on this line
                res.responseBody = Blob.valueOf('From myRest');

}
}

Test Class :

@isTest
public class TestClass{

static testmethod testdoGet(){
  TestService.doGet();
}
}

Best Answer

You will have to set up your own RestResponse and RestRequest object.

    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    req.requestURI = 'https://na11.salesforce.com';  // sample Endpoint
    req.httpMethod = 'GET';
    RestContext.request = req;
    RestContext.response = res;

    TestService.doGet();

Look at following classes to create own payload:-

Apex has provided methods here to set up your own payload for test purpose only. However, these can be used in main class but not recommended.

Related Topic