I have a Apex Class which is exposed as a Rest API, the method is current void like below
@RestResource(urlMapping='/SFDataAPI/*')
global with sharing class SFDataAPI {
@HttpGet
global static void doGet() {
String result = '';
RestRequest req = RestContext.request;
String segmentID = req.params.get('SegmentID');
List<Account> accs = [SELECT Name,Parent.Name FROM Account WHERE Data_Source_ID__c = :segmentID ];
Account acc = accs[0];
Map<String,String> resultMap = new Map<String,String> {
'Site Account Name' => acc.Name,
'Parent Account Name'=> acc.Parent.Name
};
result = JSON.serialize( resultMap);
RestContext.response.addHeader('Content-Type','application/json');
RestContext.response.responseBody = Blob.valueOf(result);
}
}
I tried writing my Test class like below
@IsTest
public class SFDataAPITest {
@IsTest static void testUnit1()
{
Test.startTest();
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = '/services/apexrest/SFDataAPI';
req.params.put('SegmentID', 'TestPAX123');
req.httpMethod = 'GET';
req.addHeader('Content-Type', 'application/json');
RestContext.request = req;
RestContext.response = res;
SFDataAPI.doGet();
//System.debug();
Test.stopTest();
}
}
I not able to do the assertion here because when I try assign the response from the API in to the String or list throws error saying Illegal assignment from void to Account
or Illegal assignment from void to String
how can I handle that here.
Best Answer
Instead of using return value, you can directly use the
RestContext
response.As per the documentation here below is true for
responseBody
property ofRestResponse
classThe response is either the serialized form of the method return value or it's the value of the responseBody property based on the following rules:
Below is the sample code to get the assert statements working
Also, you will have to create test
Acount
record with the matchingSegmentID
. So that thedoGet
method returns a record when theSOQL
executes.Hope this helps!