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
Ashutosh Tripathi 66Ashutosh Tripathi 66 

Help on the test class

Need to write a test class for the below REST class.
public class callApi {
    public String Response;
	public String apiKey;
	List<String> prospectValues = new List<String>();
    public PardotProspectWrapper wrapper {get; set;}
    public List<PardotProspectWrapper> wrapperList {get;set;}
    public List<Pardot_Prospect__c> ppobjlst {get;set;}
    //getting values from customSetting
            SFtoPardot__c pdcred = SFtoPardot__c.getInstance('PardotCredentials');
	        String email = pdcred.PardotUserName__c;
            String password = pdcred.PardotPassword__c;
            String userKey = pdcred.API_User_Key__c;
            String CreatedAfter = pdcred.Created_After__c;
            String CreatedBefore = pdcred.Created_Before__c;
			
     //Declaring wrapper for custom object Pardot_Prospect__c
	 Pardot_Prospect__c PP = new Pardot_Prospect__c();
    
    //Authenticating Pardot with Salesforce
    public void Auth() {
		    HttpRequest req = new HttpRequest();
            req.setEndpoint( 'https://pi.pardot.com/api/login/version/4' );
            req.setMethod( 'POST' );
            req.setBody( 'email=' + email + '&password=' + password + '&user_key=' + userKey );
            
            HttpResponse res = new Http().send( req );
			
		    String response = res.getBody();
            Integer startIdx = response.indexOf( '<api_key>' ) + 9;
            Integer endIdx = response.indexOf( '</api_key>' );
            String apiKey = response.substring( startIdx, endIdx );
	        System.debug('******'+apiKey );
			getAndParse(apiKey,userKey);
        }
	
    //Getting and Parsing the response received from Pardot
	public void getAndParse(String apiKey, String userKey){
		   HttpRequest req = new HttpRequest();
           HttpResponse res = new HttpResponse();
           req.setEndpoint( 'https://pi.pardot.com/api/prospect/version/4/do/query?user_key='+userKey+'&'+'api_key='+apiKey+'&'+'output=bulk&format=json&created_after='+CreatedAfter+'&'+'created_before='+CreatedBefore+'&'+'sort_by=created_at&sort_order=ascending');
           req.setMethod( 'GET' );
           req.setBody( 'user_key='+userKey+'&'+'api_key='+apiKey);
           req.setHeader('Accept', 'application/json ');
           req.setHeader('Content-Type','application/json');
		   res = new Http().send( req );
	       System.debug('***Response****'+res.getBody());
           wrapper = (PardotProspectWrapper)JSON.deserialize(res.getBody(), PardotProspectWrapper.class);
          system.debug('******Wrapper*****'+wrapper);
        
            //this I tried to add to store the data in Pardot_Prospect__c 
			ppobjlst = new List<Pardot_Prospect__c>();
           Pardot_Prospect__c ppobj = new Pardot_Prospect__c();
			for (PardotProspectWrapper.prospect p : wrapper.result.prospect) {
                ppobj = new Pardot_Prospect__c();
                ppobj.Prospect_Id__c = string.valueOf(p.id);
                ppobj.First_name__c = p.first_name;
                ppobj.Last_Name__c = p.last_name;
                ppobj.Company__c = p.company;
                ppobj.Grade__c = p.grade;
                ppobj.Score__c = p.score;
				ppobjlst.add(ppobj);
			}
			insert ppobjlst;     
		}    
    
    }

 
Balu_SFDCBalu_SFDC
Hi,

First Create HTTPMock test class and create your required resopnse like below.

@isTest
global class HttpCalloutMockTest implements HttpCalloutMock {
    
    global HTTPResponse respond(HTTPRequest req) {      
        System.assertEquals('POST', req.getMethod());       
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"success":"true"}');
        res.setStatusCode(200);
        return res;
    }
}

Use below line in your actual Test class 

Test.setMock(HttpCalloutMock.class, new <<yourClassName>>());

Hope this will helps you.
Ashutosh Tripathi 66Ashutosh Tripathi 66
thanks for the update, but here if you see I am not using "HttpResponse" as return type just one method is for authorization and another is to fetching data. Both are "void" that's it is thoriwing error.
Test.setMock(HttpCalloutMock.class, new callApiHttpCalloutMock());
        HttpResponse response = callApi.Auth(); // Error here because Auth() is void and I am taking it into HttpResponse
        System.assertEquals(200, response.getStatusCode(),'The status code is not 200.');
Is there way to fix it or I have to change the original class?
 
Raj VakatiRaj Vakati
try this
 
@isTest
global class HttpCalloutMockTest implements HttpCalloutMock {
    
    global HTTPResponse respond(HTTPRequest req) {      
        System.assertEquals('POST', req.getMethod());       
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
		// Set the excat body to parse form the code 
        res.setBody('{"success":"true"}');
        res.setStatusCode(200);
        return res;
    }
}
@istest
public class callApiTest{

 @isTest static void testCallout() {
        Test.startTest() ;
		
		Pardot_Prospect__c pri = new Pardot_Prospect__c();
		//add all fields
		insert pri ;
       
        Test.setMock(HttpCalloutMock.class, new HttpCalloutMockTest());
        callApi  sls = new callApi ();
        sls.Auth();
		
        Test.stopTest();
    }
}


 
Ashutosh Tripathi 66Ashutosh Tripathi 66
Thanks Raj, I am getting null pointer exception on 
callApi  sls = new callApi ();
I understand if I change the method return type then it will help to fetch the information in test class but I just want to cover this as it is. Please suggest your thoughts.
Raj VakatiRaj Vakati
can you give me complete code ?? 

You need to insert the SFtoPardot__c  values also then only it wlll work
Raj VakatiRaj Vakati
give me the actual http responce also in json pls  and callApiHttpCalloutMock classes
Ashutosh Tripathi 66Ashutosh Tripathi 66
HttpCalloutMock:
@isTest
global class callApiHttpCalloutMock implements HttpCalloutMock {
    // Implement this interface method
     global HTTPResponse respond(HTTPRequest req) {      
        System.assertEquals('POST', req.getMethod());       
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
		// Set the excat body to parse form the code 
        res.setBody('{"success":"true"}');
        res.setStatusCode(200);
        return res;
    }
}
I am sharing the response of 2 objects among 500 prospects received. You can check the object structure here(https://jsoneditoronline.org/) by pasting it this response.
{"@attributes":{"stat":"ok","version":1},"result":{"prospect":[{"id":1704281,"campaign_id":969,"user_id":null,"salutation":"Ms","first_name":"test","last_name":"Akin","email":"kakin@athenahome.com","company":"Aethna Home Products123","website":null,"job_title":"Director, Warehouse Mgmt","department":null,"country":"USA","address_one":null,"address_two":null,"city":null,"state":"VA","territory":null,"zip":null,"phone":"(434) 369-3100","source":"Partner Referral","annual_revenue":null,"employees":null,"industry":null,"years_in_business":null,"score":0,"grade":null,"crm_lead_fid":"00Q2800000181GmEAI","crm_contact_fid":null,"crm_owner_fid":"00528000000V4MbAAK","last_activity_at":null,"is_do_not_email":null,"is_do_not_call":null,"opted_out":null,"is_reviewed":null,"created_at":"2017-04-03 06:42:10","updated_at":"2018-01-09 01:40:29","campaign":{"id":969,"name":"Email Plug-in"},"prospect_account_id":null},
{"id":1704289,"campaign_id":969,"user_id":null,"salutation":null,"first_name":"test","last_name":"test","email":"praneetvig@gmail.com","company":"test","website":null,"job_title":"asd","department":null,"country":null,"address_one":null,"address_two":null,"city":null,"state":null,"territory":null,"zip":null,"phone":"(434) 369-3100","source":"Phone Inquiry","annual_revenue":null,"employees":null,"industry":null,"years_in_business":null,"score":0,"grade":null,"crm_lead_fid":"00Q28000001OpNqEAK","crm_contact_fid":null,"crm_owner_fid":"00528000000V4MbAAK","last_activity_at":null,"is_do_not_email":null,"is_do_not_call":null,"opted_out":null,"is_reviewed":null,"created_at":"2017-04-03 06:46:46","updated_at":"2018-01-09 01:40:29","campaign":{"id":969,"name":"Email Plug-in"},"prospect_account_id":null}]}}
Raj VakatiRaj Vakati
try this
 
@isTest
global class callApiHttpCalloutMock implements HttpCalloutMock {
    // Implement this interface method
     global HTTPResponse respond(HTTPRequest req) {      
        System.assertEquals('POST', req.getMethod());       
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
		// Set the excat body to parse form the code 
        res.setBody('{"@attributes":{"stat":"ok","version":1},"result":{"prospect":[{"id":1704281,"campaign_id":969,"user_id":null,"salutation":"Ms","first_name":"test","last_name":"Akin","email":"kakin@athenahome.com","company":"Aethna Home Products123","website":null,"job_title":"Director, Warehouse Mgmt","department":null,"country":"USA","address_one":null,"address_two":null,"city":null,"state":"VA","territory":null,"zip":null,"phone":"(434) 369-3100","source":"Partner Referral","annual_revenue":null,"employees":null,"industry":null,"years_in_business":null,"score":0,"grade":null,"crm_lead_fid":"00Q2800000181GmEAI","crm_contact_fid":null,"crm_owner_fid":"00528000000V4MbAAK","last_activity_at":null,"is_do_not_email":null,"is_do_not_call":null,"opted_out":null,"is_reviewed":null,"created_at":"2017-04-03 06:42:10","updated_at":"2018-01-09 01:40:29","campaign":{"id":969,"name":"Email Plug-in"},"prospect_account_id":null},{"id":1704289,"campaign_id":969,"user_id":null,"salutation":null,"first_name":"test","last_name":"test","email":"praneetvig@gmail.com","company":"test","website":null,"job_title":"asd","department":null,"country":null,"address_one":null,"address_two":null,"city":null,"state":null,"territory":null,"zip":null,"phone":"(434) 369-3100","source":"Phone Inquiry","annual_revenue":null,"employees":null,"industry":null,"years_in_business":null,"score":0,"grade":null,"crm_lead_fid":"00Q28000001OpNqEAK","crm_contact_fid":null,"crm_owner_fid":"00528000000V4MbAAK","last_activity_at":null,"is_do_not_email":null,"is_do_not_call":null,"opted_out":null,"is_reviewed":null,"created_at":"2017-04-03 06:46:46","updated_at":"2018-01-09 01:40:29","campaign":{"id":969,"name":"Email Plug-in"},"prospect_account_id":null}]}}');
        res.setStatusCode(200);
        return res;
    }
}
 
@isTest
public class callApiTest {
   @isTest static void testCallout() {
        Test.startTest() ;
		
		Pardot_Prospect__c pri = new Pardot_Prospect__c();
		
       pri.First_Name__c = 'Test';
       pri.Last_Name__c = 'Prospect';
       pri.Company__c = 'Test Company';
       pri.Email__c = 'ashu@gmail.com';
       pri.Grade__c = 'A+';
       pri.Score__c = 102.00;
       pri.Prospect_Id__c = '1234556';
		insert pri ;
       
          SFtoPardot__c pdcred = new SFtoPardot__c();
            pdcred.Name = 'PardotCredentials';
	        pdcred.PardotUserName__c = 'xyz@gmail.com';
            pdcred.PardotPassword__c = 'xyzw';
            pdcred.API_User_Key__c = '12341f89c1d1a5c4a6667199886a4675';
            pdcred.Created_After__c='2012-01-01T00:00:00';
            pdcred.Created_Before__c='2019-12-31T00:00:00';
            insert pdcred;
       
        Test.setMock(HttpCalloutMock.class, new callApiHttpCalloutMock());
        callApi  sls = new callApi ();
        sls.Auth();
		
        Test.stopTest();
    }
}