Sunday, 2 December 2012

Writing Test Classes For Apex Rest Service

I came across a question in a developer community on how to write Unit Test Classes for the Rest API service for POST HTTP calls

Unit Test Classes for REST API following link is very useful and inspired by this jeff had an article on his blog on how to write the test method for same .

Here is the Jeff Blog Link Test Class for REST API(Good reference for GET Rest Services)

In one of my previous blog post i demonstrated how to use native parsing technique for Rest api for User Defined Type
I wrote the Test class for the same and this post is helpful for all those searching for how to write test classes for apex rest service annotated with POST Call
Here is the Rest Service Class for which i attempted the test class
global with sharing class MyRestResourcedemo {

    global class RequestWrapper{
       public  Account acct;
        public Contact[] cons;
   global class ResponseWrapper {           
        public String StatusCode;
        public String StatusMessage;
        public Account acct;
        public Contact[] cons;    

    global static ResponseWrapper doPost(RequestWrapper reqst) {
        ResponseWrapper resp = new ResponseWrapper();     
        insert reqst.acct;
        for(Contact c:reqst.cons){
        c.AccountId = reqst.acct.Id;
        Upsert reqst.cons;
        catch( Exception e ) {
                resp.statusCode = 'Error';
                resp.statusMessage = 'Exception : ' + e.getMessage();
            resp.statusCode = 'Done';
            resp.statusMessage = 'Test success message';
            resp.acct = reqst.acct;
            resp.cons = reqst.cons;

        return resp;

Here is how i wrote my Test class and it ensured my class is covered and i aserted the response
public class SFA_TestRestPostService {
   static testMethod void  testPostRestService(){
   Account acc=new Account();'Test';
   List lstcon=new List();

   integer i;
   Contact c=new Contact();
   MyRestResourcedemo.RequestWrapper reqst=new MyRestResourcedemo.RequestWrapper();
   String JsonMsg=JSON.serialize(reqst);
   //As Per Best Practice it is important to instantiate the Rest Context 
   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();
   req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
   req.httpMethod = 'POST';//HTTP Request Type
   req.requestBody = Blob.valueof(JsonMsg);
   RestContext.request = req;
   RestContext.response= res;

   MyRestResourcedemo.ResponseWrapper resp =new  
   resp=MyRestResourcedemo.doPost(reqst); //Call the Method of the Class with Proper       Constructor 
   System.assert(resp.statusMessage.contains('Test success message'));//Assert the response has message as expected 
   System.assert(resp.acct.Id!=null);//Assert that the Account is inserted and has Id

Some thoughts on best practice can be found on this link of stackexchange


  1. Can you provide an example of how the JSON string would be constructed, in particular when creating multiple contacts. I'm using cURL to post data using your sample code and can't figure it out?

    1. cURL will be tedious to use .Try using salesforce workbench .The REST utility embedded in workbench is good tool to test.

      Try using the JSON.Serialise method to generate the JSON.

      List lstcnts=[Select Id,Name from contact limit 10];
      String body=JSON.Serialise(lstcnts);

      This should help you


Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...