function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ankaiah bandi 6ankaiah bandi 6 

Could you please tell me how to write test class for restresource api

@RestResource(urlMapping='/sfdcCallingContact/*')
global class GetContactFromUKOrg{


@HttpPost
  global static String insertContact()
  {
    System.debug('entered..'+RestContext.request.requestBody.toString().trim());
    String jsonBody = RestContext.request.requestBody.toString().trim();
    System.debug('jsonBody'+jsonBody );
     
  
    List<Contact> ConObj = (List<Contact>)JSON.deserialize(jsonBody,List<Contact>.class);
      
       List<Contact> ConObjInsert = new List<Contact>();
       List<Contact> ConObjUpdate = new List<Contact>();
        
   
   Iterator<Contact> keys = ConObj.iterator();
              while(keys.hasNext()){
                  Contact key = keys.next();
                 if(key.Id != null){
                       ConObjUpdate.addAll(Conobj);
                 }else {
                       ConObjInsert.addAll(ConObj);
                 }
            }
      try{
          if(ConObjUpdate != null){
              update ConObjUpdate;
          }
          if(ConObjInsert != null){
              insert ConObjInsert;
              return JSON.serialize(ConObjInsert);
          }   
      }catch(Exception e){
         return JSON.serialize('Error while creating Contact');
      } 
          
          
     return 'Success';
  }
  
 
  
}
Amit Singh 1Amit Singh 1
Hello,

You can write test class like below.

Note:- You may need make some changes. You can modify this test class as per your requirement.
 
@isTest

private class GetContactFromUKOrgTest {

    static testMethod void myUnitTest() {
         RestRequest req = new RestRequest(); 
         RestResponse res = new RestResponse();

         req.addHeader('httpMethod', 'POST');
         req.requestUri = '/services/apexrest/sfdcCallingContact/';       
         String postData = 'Your actual request which covers both scenario in JSON format';
         String JsonMsg=JSON.serialize(postData);
         req.requestBody = Blob.valueof(JsonMsg);
         RestContext.request = req; 
         RestContext.response= res;
         Test.startTest();
         GetContactFromUKOrg.insertContact();
         Test.stopTest();
   }

}

Also, refer below link for more info.
http://cloudyworlds.blogspot.in/2012/12/writing-test-classes-for-apex-rest.html

Let me know if this helps :)
Thanks,
Amit Singh
 
ankaiah bandi 6ankaiah bandi 6
Hi Amith, Thanks for the respose..i followed your steps but still i am getting the below error System.JSONException: Malformed JSON: Expected '[' at the beginning of List/Set Class.System.JSON.deserialize: line 15, column 1 Class.SalesforceOrg.insertAccount: line 10, column 1 Class.Test_SalesforceOrg1.myUnitTest: line 17, column 1 my  class and test class is below @RestResource(urlMapping='/sfdcCalling/*') global class SalesforceOrg{ @HttpPost   global static String insertAccount()   {     System.debug('entered..'+RestContext.request.requestBody.toString().trim());     String jsonBody = RestContext.request.requestBody.toString().trim();     System.debug('jsonBody'+jsonBody );            List accObj = (List)JSON.deserialize(jsonBody,List.class);               List accObjInsert = new List();        List accObjUpdate = new List();             //Account accObj = (Account)JSON.deserialize(jsonBody,Account.class);    Iterator keys = accObj.iterator();                                               while(keys.hasNext()){                                                   account key = keys.next();                                                  if(key.Id != null){                                                        accObjUpdate.addAll(accobj);                                                  }else {                                                        accObjInsert.addAll(accObj);                                                  }                                             }       try{                  if(accObjUpdate != null){               update accObjUpdate;           }           if(accObjInsert != null){               insert accObjInsert;               return JSON.serialize(accObjInsert);           }                     }catch(Exception e){               system.debug('errrrrrrrrrrr'+e);              return JSON.serialize('Error while creating Case' +e);       }                             return 'success';   }         } test class | @isTest private class Test_SalesforceOrg1 {     static testMethod void myUnitTest() {          RestRequest req = new RestRequest();           RestResponse res = new RestResponse();          req.addHeader('httpMethod', 'POST');          req.requestUri = 'https://cs82.salesforce.com/services/apexrest/sfdcCallingContact/';                String postData = '[{"Total_Cars_In_Fleet__c":"20","LCV_fleet_size__c":"20","Local_code__c":null,"Industry":"Leasing","Type":"Customer","Post_code__c":"24242","Country__c":"United Kingdom (The)","City__c":"chennai","Average_holding_period_PC_NKA__c":"12 months","RecordTypeId":"0123E0000008dde","Name":"testing Acc","CPM_Account_Id__c":"0010E000001QY3IQAW"}]';          String JsonMsg=JSON.serialize(postData);          req.requestBody = Blob.valueof(JsonMsg);          RestContext.request = req;           RestContext.response= res;          Test.startTest();          SalesforceOrg.insertAccount();          Test.stopTest();    } }can you help me on thisThanks,Bandi |
Amit Singh 1Amit Singh 1
Hello,

Seems that your JSON file that you have inserted into Apex test clas in invalid.

Please make sure that you are using the same JSON as you are using at the time of testing the functionaloty.

Thanks
AMit Singh