I was writing test classes for my apex Rest Service that i had built for an ipad app.
I noted very interesting things while experimenting.Before anything i just did a google and found an interesting blog post by Jeff
http://blog.jeffdouglas.com/2012/03/21/writing-unit-tests-for-v24-apex-rest-services/
@RestResource(urlMapping='/v.9/member/*/results/*')
global with sharing class MemberRestSvc {
@HttpGet
global static ReturnClass doGet() {
String[] uriKeys = RestContext.request.requestURI.split('/');
// get the member name from the uri
String memberName = uriKeys.get(uriKeys.size()-3);
// do awesome programming stuff here & catch any exceptions
try {
List<Contact> contacts = [Select Id From Contact where member_name__c = :memberName];
return new ReturnClass('true', 'Query executed successfully.', contacts);
} catch (Exception e) {
return new ReturnClass('false', e.getMessage(), null);
}
}
global class ReturnClass {
global String success;
global String message;
global List<Contact> records;
global ReturnClass(String success, String message, List<Contact> records) {
this.success = success;
this.message = message;
this.records = records;
}
}
}
And here is the test class
@isTest
private class Test_MemberRestSvc {
static {
// setup test data
}
static testMethod void testDoGet() {
RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = 'https://cs9.salesforce.com/services/apexrest/v.9/member/me/results/today';
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = res;
MemberRestSvc.ReturnClass results = MemberRestSvc.doGet();
System.assertEquals('true', results.success);
System.assertEquals(10, results.records.size());
System.assertEquals('Query executed successfully.', results.message);
}
}
I just commented few lines and ran and still i achieved test coverage so my question is why do i need to simply instantiate Rest request and response objects since i am directly calling the class
@isTest
private class Test_MemberRestSvc {
static {
// setup test data
}
static testMethod void testDoGet() {
/*RestRequest req = new RestRequest();
RestResponse res = new RestResponse();
req.requestURI = 'https://cs9.salesforce.com/services/apexrest/v.9/member/me/results/today';
req.httpMethod = 'GET';
RestContext.request = req;
RestContext.response = res;
*/Commented the code meant for REST apex intialization and merely calling the method!!
MemberRestSvc.ReturnClass results = MemberRestSvc.doGet();
System.assertEquals('true', results.success);
System.assertEquals(10, results.records.size());
System.assertEquals('Query executed successfully.', results.message);
}
}
Can someone explain this behaviour?Also what are the best practices for writin Test classes for apex Rest services ?