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
Tom SimmonsTom Simmons 

Help with test coverage on batch class

All, need help. Below is my callout class which makes two different callouts to external system. In callout 1, it gets a token. In Callout 2, it uses that token to retrieve the actual data. For some reason, I`m not getting a complete test coverage on this class. After line " deserializeResults3 = (accountParser)System.JSON.deserialize(fieldValue, accountParser.class);", nothing is being covered. Can someone please help? Any help is much appreciated.
 
global class CalloutsAccounts1 implements Database.Batchable<sObject>,Database.AllowsCallouts{
   global Database.QueryLocator start(Database.BatchableContext BC){
        String query =  'SELECT Id FROM Account';
        return Database.getQueryLocator(query); 
   }

   global void execute(Database.BatchableContext BC, List<Account> scope){
        HttpRequest obj = new HttpRequest(); 
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        String reqBody = '{ "user": "sales_user", "password": "sales_password" }';
        obj.setMethod('POST');
        obj.setHeader('Content-Type','application/json');
        obj.setEndPoint('https://test.samplepoint.com/api/UserSrvs.svc/Login');
        obj.setBody(reqBody);
        obj.getheader('Auth-Token');
        res = http.send(obj);
                                system.debug('Oauth Response: '+res.getbody());
                               system.debug('Header Auth-Token Response: '+res.getHeader('Auth-Token'));

                authtoken objAuthenticationInfo = (authtoken)JSON.deserialize(res.getbody(), authtoken.class);
                System.debug('objAuthenticationInfo: '+objAuthenticationInfo);


                                String token = res.getHeader('Auth-Token');
                                system.debug('token: '+token);    


        Http h1 = new Http();
        HttpRequest req1 = new HttpRequest();
        String reqBody2 = '{"Accountype" : "workforce"}'; 
        req1.setHeader('Auth-Token', token);
        req1.setHeader('Content-Type','application/json');
        req1.setMethod('POST');
         req1.setBody(reqBody2);

        req1.setEndpoint('https://test.samplepoint.com/api/accservices.svc/accountfeed');
        system.debug('======req1========'+req1);
        HttpResponse res1 = h1.send(req1);
        system.debug('==========res1============'+res1.getBody());



                   JSONParser parser = JSON.createParser(res1.getBody());
                    parser.nextToken();
                     parser.nextValue();
                            system.debug('==========parser============'+parser);

                    String fieldName = parser.getCurrentName();
                    String fieldValue = parser.getText(); 
        system.debug('==========fieldValue============'+fieldValue);
    accountParser deserializeResults3 =  new accountParser();
    deserializeResults3 = (accountParser)System.JSON.deserialize(fieldValue, accountParser.class);

     List <accountParser.cls_account> advisorList = new List<accountParser.cls_account>();
    advisorList = deserializeResults3.root.accounts.account;

           Map <Decimal,Id> AdvisorMap = New Map  <Decimal,Id>   ();

        List <Account> advisorAccList = [SELECT Id, Fact_Finder_Client_ID__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009tw6[![enter image description here][1]][1]'];

        For (Account Acs : advisorAccList) {
            If (Acs.Fact_Finder_Client_ID__c != null)
            AdvisorMap.put(Acs.Fact_Finder_Client_ID__c, Acs.ID);
            system.debug('@@@'+AdvisorMap);
                }
             Map <String,Id> HouseholdMap = New Map  <String,Id>   ();

        List <Account> advisorAccList1 = [SELECT Id, SSN__c, RecordTypeID FROM Account WHERE RecordTypeid = '012410000009Yr4'];

        For (Account Acs1 : advisorAccList1) {
            If (Acs1.SSN__c != null)
            HouseholdMap.put(Acs1.SSN__c, Acs1.ID);
                }

List<Financial_Account__c> lstAccount = new List<Financial_Account__c>();
for(accountParser.cls_account cand : advisorList){
    Financial_Account__c PFA = New Financial_Account__c();
    //PFA.Cirrus_Unique_ID__c =  cand.account_id;

    //Map Advisor Lookup
   PFA._Advisor_ID__c = cand.advisor_id; 
   PFA.Advisor__c = AdvisorMap.get(PFA._Advisor_ID__c );  

    //Map Household Client Lookup
    PFA._Household_ID2__c = cand.household_id;
   if (HouseholdMap.get(PFA._Household_ID2__c) == null) {
       PFA.Client__c = '0013C000003wagf'; 
} else if (PFA._Household_ID2__c != null) {
         PFA.Client__c = HouseholdMap.get(PFA._Household_ID2__c);  
}


    PFA._Unique_ID__c =  cand.account_id;
    PFA.Financial_Account_Number__c =  cand.account_num;
    PFA.Account_Type__c =  cand.account_type;
    PFA.Tax_Status__c=  cand.taxable_flg;
    PFA.Investment_Objective__c =  cand.objective;
    if (cand.inception_date != null) {
    PFA.Account_Opening__c = date.parse(cand.inception_date);
        }
        if (cand.perf_begin_date != null) {
    PFA._perf_begin_date__c = date.parse(cand.perf_begin_date);
        }
     }
    PFA.Account_Type__c =  cand.account_type;
    PFA.compute_flg__c = cand.compute_flg;
    PFA.Account_Description__c = cand.description;
    PFA.fwc_hh_id__c = cand.fwc_hh_id;


    lstAccount.add(PFA);
}


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                System.debug('Re-trying');
                if(isUpsertfirstTime){
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;
              }
}


   }       

   global void finish(Database.BatchableContext BC){
              CalloutsAccounts2 myContactBatch = new CalloutsAccounts2();
      Id batchProcessId = Database.executeBatch(myContactBatch);

   }
Mock:
 
@isTest
global class Example1_HttpCalloutMock implements HttpCalloutMock {

    //  Implement this interface method
    global HttpResponse respond(HttpRequest req) {

        //  Prepare a response to return
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');

        //  Can use the HttpRequest details to shape the response
        if (req.getMethod() == 'POST' && req.getEndpoint() == 'https://test.samplepoint.com/api/UserSrvs.svc/Login') { 

            //  Provide a response for this endpoint
        res.setBody('{"User":{"indenty":250751503,"GroupID":0,"IdentityProviderID":0,"IdentityProviderUserID":"test","FirstName":"test","LastName":"Services","Email":"test@test.com","AffiliateId":111,"Type":14,"SubType":1,"Gender":"M","InUseFlg":false},"AffiliatePreferences":null}');
     res.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');
        res.setStatusCode(200);                  
        }


          if (req.getMethod() == 'POST' && req.getEndpoint() == 'https://test.samplepoint.com/api/accservices.svc/accountfeed') { 
                        res.setHeader('Content-Type', 'application/json');
            //  Provide a response for this endpoint
        res1.setHeader('Content-Type', 'application/json');
res1.setBody('{  "d": "{\"root\":{\"pagination\":{\"accounts\":{\"pages\":\"111\"},\"page\":\"1\",\"pageSize\":\"2\"},\"accounts\":{\"account\":[{\"account_id\":\"512\",\"account_num\":\"35111516\",\"account_type\":\" Remainder Trust\",\"taxable_flg\":\"1\",\"compute \":\"0\",\"description\":\"ZZ-test, dave B\",\"add_id\":\"57\",\"fwc_id\":\"test-test\",\" begin_date\":\"07/10/2003\",\"inc_date\":\"07/09/2003\",\"termination_date\":\"02/24/2014\",\"last_date\":\"04/30/2008\",\"test_id\":\"18\",\"planning_id\":\"1175\",\"account_num\":\"20696291\",\"objective\":\"WCM \"},{\"account_id\":\"513\",\"account_num\":\"1515661\",\"account_type\":\"Individual Account\",\"taxable_flg\":\"1\",\" compute\":\"0\",\"description\":\"ZZ-tst, dave B\",\"add_id\":\"57\",\"fwc _id\":\"NWCP - test\",\" begin_date\":\"06/30/2003\",\" inc_date\":\"07/09/2006\",\"termination_date\":\"02/24/2014\",\"last_date\":\"04/30/2008\",\"test_id\":\"18\",\"planning_id\":\"175\",\" account_num\":\"1251515\",\"objective\":\"test\"}]}}}"}');
     res1.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');
        res1.setStatusCode(200);              
        }


        return res;
    }
}
Test class:
 
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
      Test.startTest();
       Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
       CalloutsAccounts1 CA= new CalloutsAccounts1 ();
       Account acc = new Account( Name = 'My Test Account' );
       Insert acc;
        Database.executeBatch(new CalloutsAccounts1 (), 100);
       Test.stopTest();

    }
}
User-added image


 
Tom SimmonsTom Simmons

accParser Class:
public class accParser{
	public cls_rut root;
	public class cls_rut {
		public cls_pagination pagination;
		public cls_accounts accounts;
	}
	public class cls_pagination {
		public cls_accounts accounts;
		public String page;	//1
		public String pageSize;	//2
	}
	public class cls_accounts {
		public cls_account[] account;
	}
	public class cls_account {
		public String account_id;	//52
		public String account_num;	//20696291
		public String account_type;	//test cass 
		public String taxable_flg;	//1
		public Integer compute;	//0
		public String description;	//afgag awgawg 
		public Integer add_id;	//57
		public String fwc_id;	//awga awgagw
		public String begin_date;	//07/10/2003
		public String inc_date;	//07/09/2003
		public String termination_date;	//02/24/2014
		public String last_date;	//04/30/2008 
		public Decimal test_id;	//18
		public String planning_id;	//175
		public String account_num2;	//20696291
		public String objective;	//www gwagag 
        public Integer rebal_method;	//www gwagag 
		public String	household_id;

	}
	public static accParser parse(String json){
		return (accParser) System.JSON.deserialize(json, accParser.class);
	}

	
}

authtoken Class:
 
public class authtoken {
	public static void consumeObject(JSONParser parser) {
		Integer depth = 0;
		do {
			JSONToken curr = parser.getCurrentToken();
			if (curr == JSONToken.START_OBJECT || 
				curr == JSONToken.START_ARRAY) {
				depth++;
			} else if (curr == JSONToken.END_OBJECT ||
				curr == JSONToken.END_ARRAY) { 
				depth--;
			}
		} while (depth > 0 && parser.nextToken() != null);
	}

	public String d {get;set;} 

	public authtoken(JSONParser parser) {
		while (parser.nextToken() != JSONToken.END_OBJECT) {
			if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
				String text = parser.getText();
				if (parser.nextToken() != JSONToken.VALUE_NULL) {
					if (text == 'd') {
						d = parser.getText();
					} else {
						System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
						consumeObject(parser);
					}
				}
			}
		}
	}
	
	
	public static authtoken parse(String json) {
		return new authtoken(System.JSON.createParser(json));
	}
}