Writing test coverage for Apex classes is the best feature I have seen in salesforce. In this way We ensure that our code is working fine.
However recently in Winter release salesforce provided new way for Apex Rest apis. There is no need to provide req/res parameters to the method. Below Syntax will work perfectly.
@HttpGet
global static String doGet() {
//Do stuff here....
}
But question arise how we will be writing unit tests for the same now. So for you below is the snippet which works perfectly fine. Instead of passing variables, We just need to set the RestContext object and then call the rest method. Thats all. Salesforce will automatically pass the “restContext.req” and you would be able to test your code. Happy coding.
@RestResource(urlMapping='/v.9/member/*/results/*')
global with sharing class MemberRestSvc {
@HttpGet
global static String doGet() {
String[] uriKeys = RestContext.request.requestURI.split(‘/’);
// do awesome programming stuff here
system.debug(‘uriKeys’ + uriKeys);
return ‘awesomeness-happened’;
}
static testmethod void testMemberRestsvc(){
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = ‘https://na14.salesforce.com/services/apexrest/v.9/member/me/results/today’;
req.httpMethod = ‘GET’;
RestContext.request = req;
RestContext.response = res;
String results = MemberRestSvc.doGet();
System.assertEquals(‘awesomeness-happened’,results);
}
}
You can consider this discussion link to have more understanding.