RSS

writing test cases for Apex Rest classes

23 Mar

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.

Advertisements
 
Leave a comment

Posted by on March 23, 2012 in force.com, salesforce, TechIssues

 

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: