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
@RestResource(urlMapping='/DemoUrl/*')
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;    
    }

@HttpPost
    global static ResponseWrapper doPost(RequestWrapper reqst) {
    
        ResponseWrapper resp = new ResponseWrapper();     
        try{
        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
@istest
public class SFA_TestRestPostService {
 
   static testMethod void  testPostRestService(){
   
   Account acc=new Account();
   acc.name='Test';
   acc.AccountNumber='1232332';
   acc.Site='site';
   acc.Website='cloudyworlds.blogspot.in';
   
   List lstcon=new List();

   integer i;
   for(i=0;i<=10;i++){
   Contact c=new Contact();
   c.lastname='Test+i';
   lstcon.add(c);
   }
   
   MyRestResourcedemo.RequestWrapper reqst=new MyRestResourcedemo.RequestWrapper();
   reqst.acct=acc;
   reqst.cons=lstcon;
   
   String JsonMsg=JSON.serialize(reqst);
   
   Test.startTest();
   
   //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  
   MyRestResourcedemo.ResponseWrapper(); 
   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.statusCode.contains('Done'));
   System.assert(resp.acct.Id!=null);//Assert that the Account is inserted and has Id
   Test.stopTest();
   
   }
 }

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

http://salesforce.stackexchange.com/questions/4988/writing-test-classes-for-apex-restservice

21 comments:

  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?

    ReplyDelete
    Replies
    1. https://workbench.developerforce.com/ 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

      Delete
  2. Hi Im itching to know if I may use this article in one of my blogs if I link back to you? Thanksurl

    ReplyDelete
  3. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. essay writing

    ReplyDelete
  4. Thank you for taking the time to publish this information very useful! essay writing service

    ReplyDelete
  5. The data you have posted is extremely valuable. The locales you have alluded was great. A debt of gratitude is in order for sharing... cheap essay writer

    ReplyDelete
  6. Nice post mate, keep up the great work, just shared this with my friendz cuevana peliculas on line

    ReplyDelete
  7. It is acceptable that you generally notice the positive picture of these kinds of themes yet then again on the off chance that you need related help. I truly love this post and would like to see such educational news besides. Keep it up. pro writing aid

    ReplyDelete
  8. The data you have posted is extremely valuable. The locales you have alluded was great. A debt of gratitude is in order for sharing
    promise day wishes
    hug day quotes

    ReplyDelete
  9. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. link

    ReplyDelete
  10. Perfectly define! I love the way you write! We are also an assignment writing provider in Australia, US and UK.

    Read more: Differential Equations Assignment Help

    ReplyDelete
  11. All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks buy essay cheap

    ReplyDelete
  12. There are many advantages to having professional editing services correct the proofs of your research or school essay. There are usually Teachers or professors who will review these types of tests and look for a certain tone type of argument. Having a professional writer who has experience with school tests can help you turn mediocre writing to superb writing. reddit essay writing service

    ReplyDelete
  13. I just want to let you know that I just check out your site and I find it very interesting and informative.. Atlanta Limousine

    ReplyDelete
  14. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Thanks... credit repair Michigan

    ReplyDelete
  15. Are you the one who find the SPSS Assignment complex? Here is the complete information related to the SPSS Assignment Help . Check it now.

    ReplyDelete
  16. Stressed over homework questions? Our experts got your back, from basic math to all the complicated ones. Go to our website TakeMyclassPro and select the details of your paper

    ReplyDelete
  17. Got the weekend homework blues? Do not fret. Leave the homework to us. Be it research papers, discussions, questions and bibliographies, PowerPoint presentations. TakeMyclassPro and select the details of your

    ReplyDelete

Introducing Lightning Base Components

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