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.

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" }';
        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);

        HttpResponse res1 = h1.send(req1);

                   JSONParser parser = JSON.createParser(res1.getBody());

                    String fieldName = parser.getCurrentName();
                    String fieldValue = parser.getText(); 
    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);
             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;


Boolean isUpsertfirstTime = true;
try {
    upsert lstAccount Financial_Account_Number__c;
}catch (DMLException e) {
                        upsert lstAccount Financial_Account_Number__c;
                                isUpsertfirstTime = false;


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



global class Example1_HttpCalloutMocktes 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.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');

          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
        res.setHeader('Content-Type', 'application/json');
res.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\"}]}}}"}');
     res.setHeader('Auth-Token', '6VIitOCHBJfSA7lZIlgdNLpxw+v5AvcksXlVjtnjg34qwLYHwDTHlFZYj2xC7X0nTU6djaWruJa03+FgN8cet3kwuu4N5HaAhEbldu5t8+gDH9siTt/wO58O+6872sG8=');

        return res;

Test Class:

private class CalloutClassTest {
     @isTest static void testCallout() {
       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);


SSenter image description here

  • One of the best ways to mock callouts i have seen here: salesforce.stackexchange.com/questions/141330/… - sfdcfox's answer
    – Eric
    Oct 25 '16 at 3:22
  • Thank you SFDCFox. This increased my code coverage. Though it is only giving me a coverage till line 46 now. Anything after line 46 (which is "deserializeResults3 = (accParser)System.JSON.deserialize(fieldValue, accParser.class); ") is not being covered, how can I fix this? Oct 25 '16 at 15:27
  • Make sure you are setting the response to a valid JSON response so it can parse it
    – Eric
    Oct 25 '16 at 15:34
  • Review my first comment and implement that. Currently your code will never return HttpResponse res1 as you have a return statement above that and that part of the code is not reachable. With your current code you need to check the request endpoint and return the appropriate response. If you implement what I linked to in my first answer you can define what is returned within the test itself
    – Eric
    Oct 25 '16 at 19:34
  • Thank you Eric, issue is that I`m new to Apex. If its not too much to ask, could you please give me an example how I can do that? Oct 25 '16 at 19:44

Most of the discussion has been in comments but in summary:

  1. Currently your code will never return HttpResponse res1 as you have a return statement above that and that part of the code is not reachable.

With your current code you need to check the request endpoint and return the appropriate response.

  1. Check the value of the JSON string you are using against your deserialization

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.