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
EQ AdminEQ Admin 

How to pass parameters in request body for test class

Request body :

{
    "StartDate": "2019-08-01",
    "EndDate": "2019-12-03"
}

Method : Post

Need to pass these parameters in my test class not sure how i cna do this

Test clasS:

static testMethod void testPost() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/WorkdayIntegration/';
        req.httpMethod = 'POST';
        RestContext.request = req;
        //req.requestBody=('2019/05/05','2019/06/05');
        RestContext.response= res;
        APTS_InvoiceDetailsWS.APTS_WorkdayIntegrationWrapper  results = APTS_InvoiceDetailsWS.getInvoiceDetails();
      
      
  }


Method : 
Maharajan CMaharajan C
Try the below one:

String str = '{"StartDate": "2019-08-01","EndDate": "2019-12-03"}';
req.requestBody = Blob.valueof(str);    


http://cloudyworlds.blogspot.com/2012/12/writing-test-classes-for-apex-rest.html

Thanks,
Maharajan.C
EQ AdminEQ Admin
Thanks Maharajajn for your response. 

But after tryng this getting below error : 

System.JSONException: Unexpected character ('+' (code 43)): was expecting comma to separate OBJECT entries at [line:1, column:30]
Stack TraceClass.System.JSON.deserializeUntyped: line 11, column 1
Class.APTS_InvoiceDetailsWS.getInvoiceDetails: line 17, column 1
Class.APTS_InvoiceDetailsWS_test.testPost: line 26, column 1

Web Service Class :

@RestResource(urlMapping='/WorkdayIntegration/') 
global with sharing class APTS_InvoiceDetailsWS
{
 @HttpPost
    global static APTS_WorkdayIntegrationWrapper getInvoiceDetails()
    { 
         Date startDate;
         Date endDate;
         integer countHeader;
        RestRequest req = RestContext.request;        
        RestResponse res = RestContext.response;
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestBody.toString());   // fetch parameters from request body
        startDate=Date.valueOf((String)params.get('StartDate'));
        endDate=Date.valueOf((String)params.get('EndDate'));
        String approved='Approved';
        String query1='Select id,Name,EQ_TotalInvoiceAmount__c,EQ_InvoiceApprovedDate__c,Apttus_Billing__TotalDueAmount__c,Apttus_billing__status__c,CurrencyIsoCode,Apttus_Billing__ShipToAccountId__r.EQ_ClientRef__c,Apttus_Billing__ShipToAccountId__r.EQ_ShippingState__c,Apttus_Billing__InvoiceDate__c,EQ_DueDateCustom__c,EQ_TotalTaxAmount__c from Apttus_Billing__Invoice__c where EQ_InvoiceApprovedDate__c>=:startDate and EQ_InvoiceApprovedDate__c<=:endDate and EQ_TotalInvoiceAmount__c > 0 and Apttus_billing__status__c=:approved'; 
        List<Apttus_Billing__Invoice__c> invoiceObjectList1=Database.query(query1);
        APTS_WorkdayIntegrationWrapper intWrap= new APTS_WorkdayIntegrationWrapper();
        List<APTS_InvoiceWrapper> listToStoreInvoices = new List<APTS_InvoiceWrapper>();
        Integer count;

 
Danish HodaDanish Hoda
Hi there,
Please try this :
static testMethod void testPost() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/WorkdayIntegration/';
        req.httpMethod = 'POST';
        RestContext.request = req;
        String str = '{\"StartDate\": \"2019-08-01\",\"EndDate\": \"2019-12-03\"}';
        req.requestBody= Blob.valueOf(str);
        RestContext.response= res;
        APTS_InvoiceDetailsWS.getInvoiceDetails();
  }

 
EQ AdminEQ Admin
Hi Danish,

Stiill Same error , dont know what i am missing 

System.JSONException: Unexpected character ('+' (code 43)): was expecting comma to separate OBJECT entries at [line:1, column:30]
Stack TraceClass.System.JSON.deserializeUntyped: line 11, column 1
Class.APTS_InvoiceDetailsWS.getInvoiceDetails: line 17, column 1
Class.APTS_InvoiceDetailsWS_test.testPost: line 26, column 1
Danish HodaDanish Hoda
Hi,
Please check the line number at which your are getting this error, as I have compiled this code in my org and it ran properly till line - String approved='Approved';
EQ AdminEQ Admin
It is throwing at this line in main class: 

 Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(RestContext.request.requestBody.toString());

I am not sure if this is the correct format to get the parameters from req body.
Danish HodaDanish Hoda
You are doing it right, below are the screenshots from my org with test-coverage:
User-added imageUser-added image
Mercedes BenzMercedes Benz
Hello Members,
How Can I Coverrage Send Mail Class In Test Class

public static void sendEmail( Blob body ,String recordId) {
        
        system.debug('>>>>>sendEmail function calling>>>');   
        
       //SELECT id ,name,owner.Name,ownerid,owner.email from Account where id='001HF000000NQMnYAO'
        
        List<Inspection_Retail__c> lstInspectionRetails =[SELECT Id, Name,My_Visit__r.Account.Email_Id__c FROM Inspection_Retail__c where id=:recordId]; 
        
        system.debug('>>>>>lstInspectionRetails>>>'+lstInspectionRetails[0].My_Visit__r.Account.Email_Id__c);
        
        String usrEmail = userinfo.getUserEmail();
        
        String toEmail = (lstInspectionRetails[0].My_Visit__r.Account.Email_Id__c == null ) ? usrEmail : lstInspectionRetails[0].My_Visit__r.Account.Email_Id__c;
        
        system.debug('>>>>>toEmail>>>'+toEmail);
        
        OrgWideEmailAddress orgWideEmailAddress = [SELECT Id FROM OrgWideEmailAddress WHERE Address =:'noreply@hellobpcl.in' Limit 1];
        
           
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
        attach.setContentType('application/pdf');
        attach.setFileName('RIOR.pdf');
        attach.Body = body;    
        
        
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        //email.setToAddresses(new String[] { 'bvenk.jeesh@gmail.com' });
        email.setToAddresses(new String[] { toEmail });
        email.setSubject('RIOR PDF File');
        email.setHtmlBody('PFA');
        email.setOrgWideEmailAddressId(orgWideEmailAddress.Id);
        email.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });     
        
        mails.add(email);  
        
       
        
        if(!mails.isEmpty()){

            Messaging.SendEmailResult [] results = Messaging.sendEmail(mails);  
            
            system.debug('>>>>>sendEmail results>>>'+results); 
            
            if (results[0].success) {
                System.debug('The email was sent successfully');
                
            } else {
                System.debug('The email failed to send: ' +results[0].errors[0].message);
            }
        }
        
    }
    
    public Static void generateROIRNumber(){
        
        try{           
            ROIR__c roirObj=ROIR__c.getValues('ROIRNo');
            ROIR__c roirDetails=[Select Id,Seq_No__c from ROIR__c For Update];
            String sqNumber=String.valueOf(Integer.valueOf(roirDetails.Seq_No__c)+1);
            roirObj.Seq_No__c=sqNumber;
            update roirObj;            
        }Catch(Exception ex){
            system.debug('>>>generateROIRNumber Error>>>'+ex.getMessage() + ' >>> Line No >>>>> '+ ex.getLineNumber());
        }
        
    }