0

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 MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {

        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
res.setBody('{"User":{"indenty":250751503,"GroupID":0,"IdentityProviderID":0,"IdentityProviderUserID":"test","FirstName":"test ","LastName":"Services","Email":"[email protected]","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);         
        return res; 


                HttpResponse res1 = new HttpResponse();
        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 res1;


    }
}

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();

    }
}
2
  • Please update your original question and not duplicate it. If the community feels the updates meet the criteria it will be reopened
    – Eric
    Oct 25, 2016 at 19:27
  • Understood, thanks Eric. I have updated my original question. Could you please look at my original question and help me? Oct 25, 2016 at 19:32

0

Browse other questions tagged .