3

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();
}
}
8

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.

  • Thanks Ashwani !! I missed to initialize the RestContext.Response. – s_saiyan Jan 23 '17 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.