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
U ChauhanU Chauhan 

Test class for rest api callout using future method

I have written a class for salesforce to salesforce integration, i have also written test class but i am not able to get 75% code coverage please help me with this. Below is my code snap and test class.

User-added imagemock test class-
@isTest
global class HttpCalloutMockGenerator implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest request) {   
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"LastName":"Test"}');
        response.setStatus('OK');
        response.setStatusCode(200);
        return response; 
    }
}

Main Test Class
@isTest
private class SalesforceIntegrationCalloutsTest {
    
    @isTest static void testPostCallout() {
        Test.setMock(HttpCalloutMock.class, new HttpCalloutMockGenerator());
        test.startTest();  
        ContactCreationDestinationClass.createContactRecord('Test');
        test.stopTest();
        HttpRequest req = new HttpRequest();
        HttpCalloutMockGenerator mock = new HttpCalloutMockGenerator();
        HttpResponse res = mock.respond(req);
        // Verify that the response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        System.debug(res.getBody());
        System.assertEquals(200, res.getStatusCode());     
    }
}
Best Answer chosen by U Chauhan
AnudeepAnudeep (Salesforce Developers) 
Posting a sample code here that will generate an accesstoken
 
Test CLass
====================
@istest
public class testclassmock
{


public static testmethod void xxx()
{

Account a=new Account(name='xasxas');
insert a;
test.starttest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
testingmock.getaccesstoken();
Test.stoptest();

}


}

===================================
MockHttpResponseGenerator
================

@isTest

global class MockHttpResponseGenerator implements HttpCalloutMock {

// Implement this interface method

global HTTPResponse respond(HTTPRequest req) {

// Optionally, only send a mock response for a specific endpoint

// and method.


// Create a fake response

HttpResponse res = new HttpResponse();

res.setHeader('Content-Type', 'application/json');

res.setBody('{"access_token":"dddsadasxsaxasxasx","instance_url":"https://login.salesforce.com"}');

res.setStatusCode(200);

return res;

}

}


=======================================
testingmock
=======================

public class testingmock{
Public static string accessToken;
Public static String sfdcInstanceUrl;

Public static String clientId = EncodingUtil.urlEncode('3MVG9ZL0ppGP5UrBILx.cwUlzgnCKcsNOXH3WkC2BgoTdm2ic8.FIqbM6zHFa2TaSvABISUSw8HdOsOOdg8T.','UTF-8');
Public static String clientSecret = EncodingUtil.urlEncode('196258194978389686','UTF-8');
Public static String username = EncodingUtil.urlEncode(YYYYYYYYYYYYYYY','UTF-8');
Public static String password = EncodingUtil.urlEncode('xxxxxxxxxxxx','UTF-8');
Public static String body = 'grant_type=password&client_id=' + clientId +
'&client_secret=' + clientSecret +
'&username=' + username +
'&password=' + password;



@future(callout=true)
public static void getaccesstoken()
{

Http h = new Http();
HttpRequest hRqst = new HttpRequest();
hRqst.setEndpoint('https://login.salesforce.com/services/oauth2/token'); // caller provides, this will be a REST resource
hRqst.setMethod('POST'); // caller provides
hRqst.setTimeout(6000);
hRqst.setBody(body); // caller provides
HttpResponse hRes=h.send(hRqst);
Account a=[select id from Account limit 1];
update a;
system.debug('=========http response====='+hRes);


Map<String,String> res = (Map<String,String>) JSON.deserialize(hRes.getBody(),Map<String,String>.class);

accessToken = res.get('access_token'); // remember these for subsequent calls
sfdcInstanceUrl = res.get('instance_url');
system.debug('======access token======'+accessToken);
}


}


=================================================

Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you
 

All Answers

AnudeepAnudeep (Salesforce Developers) 
Posting a sample code here that will generate an accesstoken
 
Test CLass
====================
@istest
public class testclassmock
{


public static testmethod void xxx()
{

Account a=new Account(name='xasxas');
insert a;
test.starttest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
testingmock.getaccesstoken();
Test.stoptest();

}


}

===================================
MockHttpResponseGenerator
================

@isTest

global class MockHttpResponseGenerator implements HttpCalloutMock {

// Implement this interface method

global HTTPResponse respond(HTTPRequest req) {

// Optionally, only send a mock response for a specific endpoint

// and method.


// Create a fake response

HttpResponse res = new HttpResponse();

res.setHeader('Content-Type', 'application/json');

res.setBody('{"access_token":"dddsadasxsaxasxasx","instance_url":"https://login.salesforce.com"}');

res.setStatusCode(200);

return res;

}

}


=======================================
testingmock
=======================

public class testingmock{
Public static string accessToken;
Public static String sfdcInstanceUrl;

Public static String clientId = EncodingUtil.urlEncode('3MVG9ZL0ppGP5UrBILx.cwUlzgnCKcsNOXH3WkC2BgoTdm2ic8.FIqbM6zHFa2TaSvABISUSw8HdOsOOdg8T.','UTF-8');
Public static String clientSecret = EncodingUtil.urlEncode('196258194978389686','UTF-8');
Public static String username = EncodingUtil.urlEncode(YYYYYYYYYYYYYYY','UTF-8');
Public static String password = EncodingUtil.urlEncode('xxxxxxxxxxxx','UTF-8');
Public static String body = 'grant_type=password&client_id=' + clientId +
'&client_secret=' + clientSecret +
'&username=' + username +
'&password=' + password;



@future(callout=true)
public static void getaccesstoken()
{

Http h = new Http();
HttpRequest hRqst = new HttpRequest();
hRqst.setEndpoint('https://login.salesforce.com/services/oauth2/token'); // caller provides, this will be a REST resource
hRqst.setMethod('POST'); // caller provides
hRqst.setTimeout(6000);
hRqst.setBody(body); // caller provides
HttpResponse hRes=h.send(hRqst);
Account a=[select id from Account limit 1];
update a;
system.debug('=========http response====='+hRes);


Map<String,String> res = (Map<String,String>) JSON.deserialize(hRes.getBody(),Map<String,String>.class);

accessToken = res.get('access_token'); // remember these for subsequent calls
sfdcInstanceUrl = res.get('instance_url');
system.debug('======access token======'+accessToken);
}


}


=================================================

Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you
 
This was selected as the best answer
U ChauhanU Chauhan
Thank You Anudeep!!
I Got My Answer....
Group IT Mah SingGroup IT Mah Sing
User-added image

Its coming only 62% coverage.
Help to increase to 75%


Apex Class 
public class QPOutboundLead {
    
    public static void updateleadQP(Set<Id> LeadIds) {
        if (!LeadIds.isEmpty()) {
            for (Id LeadId : LeadIds){
                QPLead(LeadId);
                }
            }
      }
    @future(Callout = true)
    public static void QPLead(Id LeadId) {
                 
        
          try {
              
              List<QPLeads__c> Leads = new List<QPLeads__c>();
              List<QPLog__c> sentMessagesList = new List<QPLog__c>();
              
              Leads = [SELECT SurveyType__c,EmailTrigger__c,SMSTrigger__c,EmailTemplateID__c,Email__c,FirstName__c,Id,LastName__c,LeadID__c,Mobile__c,Name,SegmentCode__c,SmsTemplateID__c,SurveyID__c,SentStatus__c FROM QPLeads__c where id=:LeadId];
              System.debug('QP Leads '+Leads);
            
            for(QPLeads__c unt:Leads){
                String bodyJson = '{ "surveyID": "'+unt.SurveyID__c+'", "sendEmail": "'+unt.EmailTrigger__c+'", "sendSMS": "'+unt.SMSTrigger__c+'", "smsTemplateID": "'+unt.SmsTemplateID__c+'", "language": "No Language", "contacts": [ { "firstName": "'+unt.FirstName__c+'", "lastName": "'+unt.LastName__c+'", "mobile": "'+unt.Mobile__c+'","email": "'+unt.Email__c+'" } ], "invitationTemplateID": "'+unt.EmailTemplateID__c+'" }';

                Api_Endpoint_Setting__mdt apisetting=[Select id,MasterLabel,EndPoint_For_Production__c,EndPoint_For_Sandbox__c,Production_Security_Code__c,Sandbox_Security_Code__c from Api_Endpoint_Setting__mdt where MasterLabel='Create_Lead'];
            String endpoint='';
            if(UtilityClass.runningInASandbox()){
                // runnig in sandbox
                endpoint = apisetting.EndPoint_For_Sandbox__c+apisetting.Sandbox_Security_Code__c;
            }else{
                //running in production
                endpoint = apisetting.EndPoint_For_Production__c+apisetting.Production_Security_Code__c;
            }
            
            System.debug('Endpoint :'+endpoint);
                
                Http http = new Http();
                HttpRequest request = new HttpRequest();
                request.setEndpoint(endpoint);
                request.setMethod('POST');
               
                request.setHeader('Content-Type', 'application/json;charset=UTF-8');
                request.setTimeout(120000);
                System.debug('QP BodyJson '+bodyJson);
                
                request.setBody(bodyJson);
                
                HttpResponse response  = http.send(request); 
                
                system.debug('response body is '+response.getBody());
                system.debug('response status code is '+response.getStatusCode());
                system.debug('To String'+response.toString());
                 
                
                JSONParserQP result = JSONParserQP.parse(response.getBody());
                system.debug('email status is '+result.Response.emailStatus);
                /*if (response.getStatusCode() != 200) {
                    System.debug('The status code returned was not expected: ' +
                        response.getStatusCode() + ' ' + response.getStatus());
                } else {
                    System.debug(response.getBody());
                    
                }*///original
                
                //newcode
                if(response.getStatusCode()== 200){
            System.debug('message sent successfully');
            //JSONParserQP result = JSONParserQP.parse(response.getBody());
     
            sentMessagesList.add(new QPLog__c(
                                              Mobile__c =unt.Mobile__c ,
                                              Email__c=unt.Email__c,
                                              LeadID__c=unt.LeadID__c,
                                              EmailStatus__c=result.Response.emailStatus,
                                              SMSStatus__c=result.Response.smsStatus,
                                              SurveyType__c=unt.SurveyType__c ));
            }
            else{
            System.debug('The status code returned was not expected: ' +
                        response.getStatusCode() + ' ' + response.getStatus());
                sentMessagesList.add(new QPLog__c(
                                              LeadID__c=unt.LeadID__c,
                                              SentStatus__c=response.getBody(),
                                              SurveyType__c=unt.SurveyType__c));
            }
            
                //newcode                
            }
              //newcode
              if(sentMessagesList.size()>0){
            insert sentMessagesList;
                  //newcode
        }
              
            } catch (Exception ex) {         
                System.debug('exception message is '+ex.getMessage());
                //your log              
            }             
        }
        }


Test Class 

/* Generated by TestGen on Tue Apr 12 2022 at 4:28 AM (GMT) */
@isTest
private class QPOutboundLead_TGN_TEST{
    private class QPOutboundLead_HCM_TGN_TEST implements HttpCalloutMock{
        protected Integer code;
        protected String status;
        protected String body;
        protected Map<String,String> headers;
        public QPOutboundLead_HCM_TGN_TEST(Integer code,String status,String body,Map<String,String> headers){
            this.code=code;
            this.status=status;
            this.body=body;
            this.headers=headers;
        }
        public HTTPResponse respond(HTTPRequest req){
            HttpResponse res=new HttpResponse();
            res.setStatusCode(this.code);
            res.setStatus(this.status);
            res.setBody(this.body);
            if(this.headers!=null){
                for(String key:this.headers.keySet()){
                    res.setHeader(key,this.headers.get(key));
                }
            }
            return res;
        }
    }
    @isTest(SeeAllData=true)
    private static void updateleadQP_TGN_TEST(){
        Database.SaveResult dsr;
        QPLeads__c drQPLeads_c;
        drQPLeads_c=new QPLeads__c();
        dsr=Database.insert(drQPLeads_c,false);
        Test.startTest();
        QPOutboundLead_HCM_TGN_TEST httpMock;
        httpMock=new QPOutboundLead_HCM_TGN_TEST(200,'Complete','null',null);
        Test.setMock(HttpCalloutMock.class,httpMock);
        try{
        QPOutboundLead.updateleadQP(new Set<Id>{dsr.getId()});
        }catch(Exception e){}
        Test.stopTest();
    }
    @isTest(SeeAllData=true)
    private static void QPLead_TGN_TEST(){
        Database.SaveResult dsr;
        QPLeads__c drQPLeads_c;
        drQPLeads_c=new QPLeads__c();
        dsr=Database.insert(drQPLeads_c,false);
        //insert new QPLog__c (Mobile__c = '12345', Email__c = 'test@test.com', SentStatus__c = 'test', LeadID__c = drQPLeads_c.Id);
        QPLog__c qpLog = new QPLog__c (Mobile__c = '12345', Email__c = 'test@test.com', SentStatus__c = 'test', LeadID__c = drQPLeads_c.Id, SentStatusCode__c  = 200);
        insert qpLog;
        Test.startTest();
        QPOutboundLead_HCM_TGN_TEST httpMock;
        httpMock=new QPOutboundLead_HCM_TGN_TEST(200,'Complete','{}',null);
        Test.setMock(HttpCalloutMock.class,httpMock);
        try{
        QPOutboundLead.QPLead(dsr.getId());
        system.assertEquals(qpLog.SentStatusCode__c,httpMock.code);
        }catch(Exception e){}
        /*try{
        QPOutboundLead.QPLead(dsr.getId());
        }catch(Exception e){}*/
        Test.stopTest();
    }
    @isTest
    private static void QPOutboundLead_TGN_TEST(){
        QPOutboundLead obj = new QPOutboundLead();
            }
}