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
trailhead solutions 10trailhead solutions 10 

Test Class for Apex rest API Http Put

Hello

Please someone help me in writing test class for this class rest api for Http put.  My Test Class is failing at 20%.

Thanks in Advance
SF Aspirant

@RestResource(urlMapping='/opportunityiWiseUpdate/*')
Global class opportunityiWiseUpdate {
    global class responseWrapper{
       global id SalesForceId;
       global Date EffectiveDate;
       global string stage;
       global date closedate;
       global Decimal ContractValue;
      }

    @httpput
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          //system.debug(wResp);
          //string id = wResp.Id;
         // system.debug(id);
     
      opportunity op = [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity where id =:wResp.SalesForceId ];
          
          if(op.id !=null){
              if(op.recordtype.Name=='H'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='I'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}



My Test Class:
@istest
public class TestUpdateBOfromiwise {
 @testsetup
    static void datasetup(){

        Profile p =[SELECT ID FROM Profile Where Name='System Administrator'];
        
        User u = new User();
        u.Alias = 'standt1';
        u.Email='sauser1@testorg.com';
        u.EmailEncodingKey='UTF-8'; 
        u.LastName='Testing1';
        u.LanguageLocaleKey='en_US';
        u.LocaleSidKey='en_US';
        u.ProfileId = p.Id;
        u.TimeZoneSidKey='America/Los_Angeles';
        u.UserName='sauser1@testorg.com';
        u.Head_Of_Region__c = 'IBSZ';
        insert u;
        
        Account a = new Account();
        a.Name = 'Test Account';
        a.Segment__c = 'Aviation';
        a.Sub_Segment__c = 'Startup';
        a.IBS_Region__c = 'IBSZ';
        a.IBS_Sub_Region__c = 'ANZ';
        a.Account_Domain_Name__c = 'test.com';
        a.Account_Code__c='Test';
        a.Approved__c = True;
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'Test Opportunity';
        o.AccountId = a.Id;
        o.Opportunity_Name__c = 'Test Record';
        o.Contract_Type__c = 'CDx Services';
        o.TCV__c = 5000;
        o.CloseDate = system.today();
        o.Type_of_Deal__c = 'New Deal';
        o.Opportunity_Source__c = 'Other';
        o.StageName = 'SQL';
        o.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o.Products__c = 'iFly Res';
        o.Incumbent__c = 'Sabre';
        o.Tenure__c = 6;
        o.Tenure_Unit_of_Measure__c = 'Years';
        o.One_Time_Fee__c = 5000;
        o.Annual_Recurring_Revenue__c = 100001;
        insert o;
        
         string name='nalini';
    }
       @isTest
    static void updateBOClassMethod(){
         
        Test.startTest();

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
  
    RestContext.request = req;
    RestContext.response= res;
 
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
}
 
Best Answer chosen by trailhead solutions 10
ravi soniravi soni
Hi Trailhead,
I made some changes in your apex Main class. don't worry logic is same. Replace your main class with following class.
@RestResource(urlMapping='/opportunityiWiseUpdate/*')
Global class opportunityiWiseUpdate {
    global class responseWrapper{
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
      public date closedate;
      public Decimal ContractValue;
      }

    @httpput
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
          system.debug('req : ' + req);
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          system.debug('wResp : ' + wResp);
          //string id = wResp.Id;
         // system.debug(id);
     //TCV__c
          for(opportunity op : [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity 
                                where id =:wResp.SalesForceId ]){
          system.debug('op : ' + op);
         // if(op.id !=null){
              if(op.recordtype.Name=='H'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='I'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}

Here is your Test Class With 100% code coverage.
@isTest
global class opportunityiWiseUpdateTest {
   @testsetup
    static void datasetup(){ 
       
        //string sHRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('FF Renewal Opportunities').getRecordTypeId();
        //string sIRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('NAL Customized Product').getRecordTypeId();
		
		string sHRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('H').getRecordTypeId();
        string sIRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('I').getRecordTypeId();
        Profile p =[SELECT ID FROM Profile Where Name='System Administrator'];
        
        list<Opportunity> lstOpp = new list<Opportunity>();
/*        User u = new User();
        u.Alias = 'standt1';
        u.Email='sauser1@testorg.com';
        u.EmailEncodingKey='UTF-8'; 
        u.LastName='Testing1';
        u.LanguageLocaleKey='en_US';
        u.LocaleSidKey='en_US';
        u.ProfileId = p.Id;
        u.TimeZoneSidKey='America/Los_Angeles';
        u.UserName='sauser1@testorg.com';
        u.Head_Of_Region__c = 'IBSZ';
        insert u;*/
        
        Account a = new Account();
        a.Name = 'Test Account';
       /*/ a.Segment__c = 'Aviation';
        a.Sub_Segment__c = 'Startup';
        a.IBS_Region__c = 'IBSZ';
        a.IBS_Sub_Region__c = 'ANZ';
        a.Account_Domain_Name__c = 'test.com';
        a.Account_Code__c='Test';
        a.Approved__c = True;*/
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'Test Opportunity';
        o.AccountId = a.Id;
        o.StageName = 'Prospecting';
        o.CloseDate = system.today() + 1;
        o.RecordTypeId = sHRecTypeId;
       /* o.Opportunity_Name__c = 'Test Record';
        o.Contract_Type__c = 'CDx Services';
        o.TCV__c = 5000;
        o.CloseDate = system.today();
        o.Type_of_Deal__c = 'New Deal';
        o.Opportunity_Source__c = 'Other';
        o.StageName = 'SQL';
        o.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o.Products__c = 'iFly Res';
        o.Incumbent__c = 'Sabre';
        o.Tenure__c = 6;
        o.Tenure_Unit_of_Measure__c = 'Years';
        o.One_Time_Fee__c = 5000;
        o.Annual_Recurring_Revenue__c = 100001;*/
        lstOpp.add(o);
           Opportunity o1 = new Opportunity();
        o1.Name = 'Test Opportunity 1';
        o1.AccountId = a.Id;
        o1.StageName = 'Prospecting';
        o1.CloseDate = system.today() + 1;
        o1.RecordTypeId = sIRecTypeId;
       /* o1.Opportunity_Name__c = 'Test Record';
        o1.Contract_Type__c = 'CDx Services';
        o1.TCV__c = 5000;
        o1.CloseDate = system.today();
        o1.Type_of_Deal__c = 'New Deal';
        o1.Opportunity_Source__c = 'Other';
        o1.StageName = 'SQL';
        o1.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o1.Products__c = 'iFly Res';
        o1.Incumbent__c = 'Sabre';
        o1.Tenure__c = 6;
        o1.Tenure_Unit_of_Measure__c = 'Years';
        o1.One_Time_Fee__c = 5000;
        o1.Annual_Recurring_Revenue__c = 100001;*/
        lstOpp.add(o1);
        insert lstOpp;
        
    }
       @isTest
    static void updateBOClassMethod(){
   Test.startTest();
 Opportunity sHOppRec= [SELECT Id,Name,recordtype.Name From Opportunity Where Name ='Test Opportunity' Limit 1];
system.debug('sHOppRec : ' + sHOppRec);        
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sHOppRec.Id,
                                                system.today(),
                                                 'Prospecting',
                                                 system.today()+1,
                                                   25);
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   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;
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
      @isTest
    static void updateBOClassMethod1(){
   Test.startTest();
 Opportunity sIOppRec= [SELECT Id,Name,recordtype.Name From Opportunity Where Name ='Test Opportunity 1' Limit 1];
        system.debug('sIOppRec : ' + sIOppRec);
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sIOppRec.Id,
                                                system.today(),
                                                 'Prospecting',
                                                 system.today()+1,
                                                   25);
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   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;
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
    
    
    public class SingleRequestMock {
        
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
      public date closedate;
      public Decimal ContractValue;
        public SingleRequestMock(id SalesForceId,  Date EffectiveDate,  string stage,
                                        date closedate,Decimal ContractValue) {
            this.SalesForceId = SalesForceId;
            this.EffectiveDate = EffectiveDate;
            this.stage = stage;
            this.closedate = closedate;
            this.ContractValue = ContractValue;
        }
    }
  
}

let me know if it helps you and marking it as best answer.
If it helps you then don't forget to marking it as best.
Thank you

All Answers

Suraj Tripathi 47Suraj Tripathi 47
Hi trailhead,
Please add "req.addHeader('Content-Type', 'application/json');" in request. 
I have modified your code, Kindly find the solution.
@isTest
    static void updateBOClassMethod(){
         
        Test.startTest();

         RestRequest req = new RestRequest(); 
         RestResponse res = new RestResponse();

         req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
         req.httpMethod = 'POST';//HTTP Request Type
         req.addHeader('Content-Type', 'application/json');

         RestContext.request = req;
         RestContext.response= res;
 
         opportunityiWiseUpdate.fetchopportunity();
       Test.stopTest();
    }
}
If You find any issue, Kindly reach out to me and
If you find your Solution then mark it as the best answer. 

Thanks and Regards
Suraj Tripathi.
trailhead solutions 10trailhead solutions 10
Hello Suraj

The above not working. Failing still.

Regards
TH Aspi
Suraj Tripathi 47Suraj Tripathi 47
Hi 

Can you add @httppost instead of @httpput 
trailhead solutions 10trailhead solutions 10
This is for updating the same record from external to sf(put)
ravi soniravi soni
Hi Trailhead,
I made some changes in your apex Main class. don't worry logic is same. Replace your main class with following class.
@RestResource(urlMapping='/opportunityiWiseUpdate/*')
Global class opportunityiWiseUpdate {
    global class responseWrapper{
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
      public date closedate;
      public Decimal ContractValue;
      }

    @httpput
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
          system.debug('req : ' + req);
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          system.debug('wResp : ' + wResp);
          //string id = wResp.Id;
         // system.debug(id);
     //TCV__c
          for(opportunity op : [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity 
                                where id =:wResp.SalesForceId ]){
          system.debug('op : ' + op);
         // if(op.id !=null){
              if(op.recordtype.Name=='H'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='I'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}

Here is your Test Class With 100% code coverage.
@isTest
global class opportunityiWiseUpdateTest {
   @testsetup
    static void datasetup(){ 
       
        //string sHRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('FF Renewal Opportunities').getRecordTypeId();
        //string sIRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('NAL Customized Product').getRecordTypeId();
		
		string sHRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('H').getRecordTypeId();
        string sIRecTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('I').getRecordTypeId();
        Profile p =[SELECT ID FROM Profile Where Name='System Administrator'];
        
        list<Opportunity> lstOpp = new list<Opportunity>();
/*        User u = new User();
        u.Alias = 'standt1';
        u.Email='sauser1@testorg.com';
        u.EmailEncodingKey='UTF-8'; 
        u.LastName='Testing1';
        u.LanguageLocaleKey='en_US';
        u.LocaleSidKey='en_US';
        u.ProfileId = p.Id;
        u.TimeZoneSidKey='America/Los_Angeles';
        u.UserName='sauser1@testorg.com';
        u.Head_Of_Region__c = 'IBSZ';
        insert u;*/
        
        Account a = new Account();
        a.Name = 'Test Account';
       /*/ a.Segment__c = 'Aviation';
        a.Sub_Segment__c = 'Startup';
        a.IBS_Region__c = 'IBSZ';
        a.IBS_Sub_Region__c = 'ANZ';
        a.Account_Domain_Name__c = 'test.com';
        a.Account_Code__c='Test';
        a.Approved__c = True;*/
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'Test Opportunity';
        o.AccountId = a.Id;
        o.StageName = 'Prospecting';
        o.CloseDate = system.today() + 1;
        o.RecordTypeId = sHRecTypeId;
       /* o.Opportunity_Name__c = 'Test Record';
        o.Contract_Type__c = 'CDx Services';
        o.TCV__c = 5000;
        o.CloseDate = system.today();
        o.Type_of_Deal__c = 'New Deal';
        o.Opportunity_Source__c = 'Other';
        o.StageName = 'SQL';
        o.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o.Products__c = 'iFly Res';
        o.Incumbent__c = 'Sabre';
        o.Tenure__c = 6;
        o.Tenure_Unit_of_Measure__c = 'Years';
        o.One_Time_Fee__c = 5000;
        o.Annual_Recurring_Revenue__c = 100001;*/
        lstOpp.add(o);
           Opportunity o1 = new Opportunity();
        o1.Name = 'Test Opportunity 1';
        o1.AccountId = a.Id;
        o1.StageName = 'Prospecting';
        o1.CloseDate = system.today() + 1;
        o1.RecordTypeId = sIRecTypeId;
       /* o1.Opportunity_Name__c = 'Test Record';
        o1.Contract_Type__c = 'CDx Services';
        o1.TCV__c = 5000;
        o1.CloseDate = system.today();
        o1.Type_of_Deal__c = 'New Deal';
        o1.Opportunity_Source__c = 'Other';
        o1.StageName = 'SQL';
        o1.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o1.Products__c = 'iFly Res';
        o1.Incumbent__c = 'Sabre';
        o1.Tenure__c = 6;
        o1.Tenure_Unit_of_Measure__c = 'Years';
        o1.One_Time_Fee__c = 5000;
        o1.Annual_Recurring_Revenue__c = 100001;*/
        lstOpp.add(o1);
        insert lstOpp;
        
    }
       @isTest
    static void updateBOClassMethod(){
   Test.startTest();
 Opportunity sHOppRec= [SELECT Id,Name,recordtype.Name From Opportunity Where Name ='Test Opportunity' Limit 1];
system.debug('sHOppRec : ' + sHOppRec);        
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sHOppRec.Id,
                                                system.today(),
                                                 'Prospecting',
                                                 system.today()+1,
                                                   25);
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   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;
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
      @isTest
    static void updateBOClassMethod1(){
   Test.startTest();
 Opportunity sIOppRec= [SELECT Id,Name,recordtype.Name From Opportunity Where Name ='Test Opportunity 1' Limit 1];
        system.debug('sIOppRec : ' + sIOppRec);
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sIOppRec.Id,
                                                system.today(),
                                                 'Prospecting',
                                                 system.today()+1,
                                                   25);
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   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;
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
    
    
    public class SingleRequestMock {
        
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
      public date closedate;
      public Decimal ContractValue;
        public SingleRequestMock(id SalesForceId,  Date EffectiveDate,  string stage,
                                        date closedate,Decimal ContractValue) {
            this.SalesForceId = SalesForceId;
            this.EffectiveDate = EffectiveDate;
            this.stage = stage;
            this.closedate = closedate;
            this.ContractValue = ContractValue;
        }
    }
  
}

let me know if it helps you and marking it as best answer.
If it helps you then don't forget to marking it as best.
Thank you
This was selected as the best answer
trailhead solutions 10trailhead solutions 10
Hi Veer Soni

Firstly, Thanking you so much that you consumed your valuable time on solving my test class code coverage.

I will check this and will update you soon.

Thanks
TH Asp
trailhead solutions 10trailhead solutions 10
Hi veer Soni

I used the code, yes I have made some few changes in the data as per my org to get the coverage. I liked the way of writing the code.

Thanks a ton!!
Sowmya BvSowmya Bv
@RestResource(urlMapping='/CaseManagement/v1/*')
global with sharing class CaseCreationAPICLs {
    @HttpPost
    global static void createCase(){
        RestRequest req = RestContext.request;
        string JsonBody = req.requestBody.toString();
        RestResponse res = RestContext.response;
        CaseJsonParser parserObj = (CaseJsonParser) System.JSON.deserialize(JsonBody, CaseJsonParser.class);
        if(parserObj != null && parserObj.caseDetails != null){
            Contact contObj = new Contact();
            contObj.FirstName = parserObj.customerDetails.firstName;
            contObj.LastName = parserObj.customerDetails.lastName;
            contObj.email = parserObj.customerDetails.email;
            insert contObj;
            Case caseObj = new Case();
            caseObj.Origin = parserObj.caseDetails.Origin;
            caseObj.Status = 'New';
            caseObj.ContactId = contObj.Id;
            insert caseObj;
            }
    }
}

please anyone help me how to write test class for this