+ Start a Discussion
trailhead solutions 10trailhead solutions 10 

How to write Test Class for Rest API

Hello

Please someone help how to cover the test class and code coverage for the below rest api class?

Thanks in Advance
TH

public class callIwiseAPI {

    //To capture getOauthToken response
    public class tokenResponse{
        public string access_token;
    }
  
  public class OpptyInput{
    String SalesForceId;
        string OpportunityType;
    String Lob;
    String Product;
    String Region;
        String SubRegion;
    String BOTitle;
  //  String BType;
    String DealNature;
  //  String BOCurrency;
    Decimal ContractValue;
    Date EffectiveDate;
    Decimal ContractDuration;
    String ContractDurationUnitOfMesurement;
  //  String AccountCode;
    String Description;
    String SalesPerson1;
    String CreatedBy;
        string ProspectName;
        String ContactPerson;
        String ContactNumber;
        String Competitors;
        String ContactEmail;
        String JobTitle;
        String AccountName;

  }
/******************************************************************************************************************
Method      : getOauthToken
Parameters  : # 
ReturnType  : object
Description : Calling iWise API to get oAuth Token and pass the same token get the BO data
*******************************************************************************************************************/
    public  String getOauthToken(){
        String oAuthToken;
        tokenResponse atResponse = new tokenResponse();
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:iWise_Credentials/token');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('username', '{!$Credential.Username}');
        request.setHeader('password', '{!$Credential.Password}');
        request.setHeader('grant_type', 'password');
    
        System.debug('Request to get oAuth Token:'+request);
        
    
        HttpResponse response = http.send(request);
        system.debug('Response from iWise for OAUTH Token:::'+response.toString());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 201 || response.getStatusCode() == 200) {
            // Deserialize the JSON string into collections of primitive data types.
            //Map<String, object> results = (Map<String, object>) JSON.deserializeUntyped(response.getBody());
            system.debug(':::: Response::::'+response.getBody());
            atResponse = (tokenResponse)json.deserialize(response.getBody(),tokenResponse.class);
            // get the oAuth tken from the response
            
            oAuthToken = atResponse.access_token;//(String) results.get('access_token');
            System.debug('OAuth Acces Token from response:'+oAuthToken);
            return oAuthToken;
            
        }
        else{
            System.debug('The status code returned was not expected: ' +
            response.getStatusCode() + ' ' + response.getStatus());
            return oAuthToken;
        }
        
    }
    
/******************************************************************************************************************
Method      : sendBoToIwise
Parameters  : oAuthToken 
ReturnType  : object
Description : Calling iWise API to send the BO
*******************************************************************************************************************/
  @future(callout = true)
    public static void sendBoToIwise(set<id> oppIds){
//    system.debug('this');
    list<Opportunity> opty = new list<Opportunity>();
       String oAuthToken;
        
    
    opty = [select Id,Name,TCV__c,IBS_Lob__c,Contract_Type__c,Competitors_Names__c,Products__c,CloseDate,Type_of_Deal__c,Tenure_Unit_of_Measure__c,Tenure__c,Description,Owner.Name,Owner.Email,Account__r.Account_Code__c,Response_from_iWise_System__c,Account.Name,
                ( SELECT contact.firstName,contact.phone,contact.Email,contact.Title,contact.IBS_Region__c,contact.IBS_Sub_Region__c FROM OpportunityContactRoles ),
                (select Name,TeamMemberRole,User.Name,User.Email   from OpportunityTeamMembers where  TeamMemberRole = 'Sales Rep')
                                                from Opportunity where Id IN : oppIds];
            system.debug(opty);
       list<OpptyInput> inputRequest = new list<OpptyInput>();
        callIwiseAPI obj = new callIwiseAPI();
        oAuthToken = obj.getOauthToken();
    if(!opty.isEmpty()){
      for(Opportunity op : opty){
        OpptyInput reqInput  = new OpptyInput();
        reqInput.BOTitle=op.Name;
        reqInput.SalesForceId=op.Id;
                reqInput.OpportunityType=op.Type_of_Deal__c;
        reqInput.Lob = op.IBS_Lob__c;
        reqInput.Product=op.Products__c;
        reqInput.Region=op.OpportunityContactRoles[0].contact.IBS_Region__c;
        reqInput.SubRegion=op.OpportunityContactRoles[0].contact.IBS_Sub_Region__c;
      //  reqInput.BType = 'New BO';
        reqInput.DealNature = op.Contract_Type__c;
      //  reqInput.BOCurrency = 'USD';
        reqInput.ContractValue = op.TCV__c;
                reqInput.EffectiveDate = op.CloseDate;
        reqInput.ContractDuration = op.Tenure__c;
        reqInput.ContractDurationUnitOfMesurement = op.Tenure_Unit_of_Measure__c ;
      //  reqInput.AccountCode= op.Account__r.Account_Code__c;
      //  reqInput.Description= op.Description;
        reqInput.SalesPerson1 =op.OpportunityTeamMembers[0].User.Email;
        reqInput.CreatedBy=op.Owner.Email;
                reqInput.ProspectName= op.Account.Name;
                reqInput.ContactPerson=op.OpportunityContactRoles[0].contact.firstName;
                reqInput.ContactNumber=op.OpportunityContactRoles[0].contact.phone;
                reqInput.Competitors=op.Competitors_Names__c;
                reqInput.ContactEmail = op.OpportunityContactRoles[0].contact.Email;
                reqInput.JobTitle=op.OpportunityContactRoles[0].contact.Title;
                reqInput.AccountName=op.Account.Name;

      inputRequest.add(reqInput);
      
      } 
    }
    String OpportunityInput = Json.serialize(inputRequest);
    System.debug('Input request to send Opportunity to iWise::'+OpportunityInput); 
    Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('Actual Endpoint to service');// also add this endpoint in remote site settings
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('Authorization', oAuthToken);
    request.setBody(OpportunityInput);
    
    System.debug('Request to send Opportunity:'+request);
    System.debug('Request body send Opportunity:'+request.getBody());
    
    HttpResponse response = http.send(request);
        system.debug('Response from iWise for Get Opportunity request:::'+response.toString());
    system.debug('Response from iWise for Get Opportunity request:::'+response.getBody());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
      System.debug('Success Response from iWise::'+response.getStatus());
        opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    else{
      System.debug('Error Response from iWise::'+response.getStatus());
      opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    if(!opty.isEmpty())
      Update opty;  
  }
}