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
andRestRequest
object.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.