+ Start a Discussion
SFDCDEVELOPERSFDCDEVELOPER 

Need test class for @HTTP post

@RestResource(urlMapping='/PostMethod/*')
global with sharing class myrestResource {

 @HttpPost   
 global static void createNewRecordl(String Email, String FirstName,String LastName) {
     
try{
     List<Person__c> tr= [Select ID, Name, Email__c from Person__c where Email__c = :Email];
     system.debug('----------'+ tr.size());
        
     if(tr.size() > 0) {
     tr[0].First_Name__c=FirstName;
     tr[0].Last_Name__c=LastName;
     update tr[0];
        Additionaldata__c tjr =new Additionaldata__c ();
      
        tjr.Email__c=Email;
        insert tjr;
        RestContext.response.addHeader('Content-Type', 'application/json');
        RestContext.response.responseBody = Blob.valueOf(JSON.serialize(tjr));
       }
     
     if(tr.size() == 0) {
        Person__c tr1= new Person__c();
        tr1.Email__c =Email;
        tr1.First_Name__c=FirstName;
        tr1.Last_Name__c=LastName;
     
        insert tr1;
        system.debug('----------'+ tr1);
        Additionaldata__c  tjr1 =new Additionaldata__c ();
    
        tjr1.Email__c=Email;
        insert tjr1;
        RestContext.response.addHeader('Content-Type', 'application/json');
        RestContext.response.responseBody = Blob.valueOf(JSON.serialize(tr1)); 
        RestContext.response.responseBody = Blob.valueOf(JSON.serialize(tjr1));     
     }
        }catch(Exception e){
            // TODO Formalize as a class if this structure proves to be durable.
            String jsonStr = 
                '{' + 
                    '"errorCode": "' + e.getTypeName() + '", ' + 
                    '"message": "' + e.getMessage() + '"' + 
                '}';
            RestContext.response.addHeader('Content-Type', 'application/json');
            RestContext.response.responseBody = Blob.valueOf(jsonStr); 
            RestContext.response.statuscode = 500;
        }       
  }  
}
NagendraNagendra (Salesforce Developers) 
Hi SFDCDEVELOPER,

Please find the below post for similar kind of issue
https://developer.salesforce.com/forums/?id=906F00000009AObIAM


Find the sample code below and modify according to your requirement.

Apex 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;
  }
}

The test class for above code will be as below
@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<contact> lstcon=new List<contact>();

   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();

   }
}


Please mark it as solved if it helps.

Best Regards,
Nagendra.P
SFDCDEVELOPERSFDCDEVELOPER
Hi Nagendra,

I tried above code but its not working.
I am not using any wrapper class in my rest class
in my case its different.