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
Salesforce Admin2Salesforce Admin2 

I need help in improving code coverage test class for batchsync class

hi I am only receiving 31% code coverage for following batch class (batchsyn) and i do not understand how to write test code that tests the API requests.
global class BatchSync implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {

public String query = 'Select Id,CaseNumber,status,Lucity_Status_code__c ,Lucity_Returned_Date__c,Lucity_Status_Type__c ,Lucity_Category_Code__c,Lucity_Prob_Code__c,Lucity_Dept_Code__c ,Lucity_Cause_Code__c,Lucity_WR_ID__c,Lucity_public_works__c,Lucity_parks__c from case where Lucity_WR_ID__c != NULL and status!=\'Closed\'';
 global Map<String,String> M = new Map<String,String>();  
     global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
     }

    global class GetLucityRequests{
        public string StatusCode;
        public string StatusType;
        public string DepartmentCode;
        public string ProblemCode;
        public string CauseCode;
        public string CategoryCode;
       
    }   
 
     global void execute(Database.BatchableContext BC, List<Case> records) {         
              
            String endpoint = null; 
            String stat2 = null;          
            List<Case> temp = new List<Case>();
            List<Authorization__c> authzn = Authorization__c.getall().values();
            String uname,pwd,works,parks;
                    if(authzn != null && authzn.size() > 0) {
                        for(Authorization__c au : authzn) {
                            uname=au.username__c;
                            pwd=au.password__c;
                            works=au.Public_works__c;
                            parks=au.Parks__c;                            
                        } 
                    }
            String before = uname+':'+pwd;
            for ( integer i = 0; i< records.size(); i++ ) {
                     if(records[i].Lucity_public_works__c == TRUE)  
                         endpoint = works+'/Work/Request.svc/?format=json&Filter=WKREQ%20WHERE%20RQ_ID%3D'+records[i].Lucity_WR_ID__c;                        
                     else 
                         endpoint = parks+'/Work/Request.svc/?format=json&Filter=WKREQ%20WHERE%20RQ_ID%3D'+records[i].Lucity_WR_ID__c;
                         
             System.debug('End Point '+endpoint + 'Record size '+records.size());    
             if(Test.isRunningTest()) {
                      GetLucityRequests r = new GetLucityRequests();
                      endpoint = works+'/Work/Request.svc/?format=json&Filter=WKREQ%20WHERE%20RQ_ID%3D'+records[i].Lucity_WR_ID__c;
              }        
             try {                  
                  HttpRequest req = new HttpRequest();
                  HttpResponse res = new HttpResponse();
                  Http http = new Http();                  
                  Blob beforeblob = Blob.valueOf(before);
                  //encode
                  String paramvalue = EncodingUtil.base64Encode(beforeblob);
                  System.debug(before + ' is now encoded as: ' + paramvalue);
                  String auth = 'Basic '+ paramvalue ;
                  req.setHeader('Authorization',auth);                   
                  req.setHeader('Content-Type', 'application/json');                                  
                  String sJson = null;  
                  Integer statCode=null;
                  String stat=null;                      
                  // req.setCompressed(true);                  
                  if (!Test.isRunningTest()) { 
                    req.setEndpoint(endpoint); 
                    req.setMethod('GET');     
                    res = http.send(req);
                    statCode = res.getStatusCode();
                    if(statCode == 200 || statCode == 201) {
                        sJson = res.getBody();                   
                        System.debug('Str:' + res.getBody());
                        sJson = sJson.replace('[','');
                        sJson = sJson.replace(']','');
                        System.debug('String JSON: ' + sJson);
                        // Parse response.  
                        GetLucityRequests aResponse = (GetLucityRequests) Json.Deserialize(sJson, GetLucityRequests.class);                    
                        if((records[i].Lucity_Status_code__c != Integer.ValueOf(aResponse.StatusCode)) || (records[i].Lucity_Status_Type__c != aResponse.StatusType)) {
                            records[i].Lucity_Status_code__c = Integer.ValueOf(aResponse.StatusCode);
                            records[i].Lucity_Status_Type__c = aResponse.StatusType;
                            if((aResponse.StatusCode == '10') && (records[i].Lucity_Dept_Code__c != aResponse.DepartmentCode)) {
                                records[i].Lucity_Dept_Code__c = aResponse.DepartmentCode;
                            }
                            if((aResponse.StatusCode == '10') && (records[i].Lucity_Prob_Code__c!= aResponse.ProblemCode)) {
                                records[i].Lucity_Prob_Code__c= aResponse.ProblemCode;
                            }
                            if((records[i].Lucity_Parks__c == TRUE) && (aResponse.StatusCode == '10') && (records[i].Lucity_Cause_Code__c!= aResponse.CauseCode)) {
                                records[i].Lucity_Cause_Code__c= aResponse.CauseCode;
                            }
                            if((records[i].Lucity_Parks__c == TRUE) && (aResponse.StatusCode == '10') && (records[i].Lucity_Category_Code__c!= aResponse.CategoryCode)) {
                                records[i].Lucity_Category_Code__c= aResponse.CategoryCode;
                            }
                            if(aResponse.StatusCode == '952') {
                                records[i].Lucity_Returned_Date__c= System.NOW();
                            }
                             System.debug('Lucity Status code '+ records[i].Lucity_Status_code__c);
                            temp.add(records[i]);               
                            System.debug('TEMP '+temp);
                        }  
                       System.debug('Status code '+aResponse.StatusCode + 'Status Type ' +aResponse.StatusType + 'Department code ' + aResponse.DepartmentCode);              
                    }
                    else {
                        stat = 'Status Code: ' + statCode + '. \n Status: ' + res.getStatus() + '. \n Cause of Error might be: Invalid URL/Server Down/Case doesn\'t exist in Lucity Server.\n\r';
                        M.put(records[i].CaseNumber,stat);
                        system.debug('STAT ' + stat + ' MAP ' + M + ' CaseNumber ' +  records[i].CaseNumber);
                    }                               
                  }             
          }
          catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );             
                  
          }
       }
      if(temp.size() > 0) {  
          Database.SaveResult[] srList = null;
          try {         
            srList = Database.update(temp,false);
          }
          catch(Exception ex)    {             
                for (Database.SaveResult sr : srList) {
                    if (!sr.isSuccess()) {
                        // Operation failed, so get all errors                
                        for(Database.Error err : sr.getErrors()) {
                            System.debug('The following error has occurred.');                    
                            System.debug(err.getStatusCode() + ': ' + err.getMessage());
                            System.debug('Case fields that affected this error: ' + err.getFields());
                            stat2 = 'Error occurred during updation.Details are as follows \n Status code: ' + err.getStatusCode() + '\n Error Message ' + err.getMessage() + '\nCase fields that affected this error: ' + err.getFields();
                            String cNum = sr.getId();
                            List<Case> casNum = [Select CaseNumber from Case where Id=: cNum];
                            M.put(casNum[0].CaseNumber,stat2);
                        }
                        sendErrorEmail(M);
                    }
                }    
          }  
      } 
       System.debug('Updated and Future boolean is '+ CaseFieldUpdate.inLucityFutureContext );
    }   

    global void finish(Database.BatchableContext BC){
        CaseFieldUpdate.inLucityFutureContext = false;
        system.debug('MAP AT FINISH ' + M + ' SIZE' + M.size());
        if (!Test.isRunningTest())
            sendErrorEmail(M);          
    }
    
  public void sendErrorEmail(Map<String,String> M) {      
        String[] toAddresses = getMailAddresses();
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();             
        mail.setToAddresses(toAddresses);
        mail.setUseSignature(false);
        mail.setBccSender(true);
        mail.setSaveAsActivity(false);   
        Authorization__c aut = Authorization__c.getValues('Lucity');
        String sub = aut.Email_Subject__c;
        System.debug(sub);               
        mail.setSubject('Batch Job Error Summary '+ sub);
        String mailBody = '';
        system.debug('MAP ' + M + ' Size ' + M.size());
        if(M.size() > 0) {
            mailBody = 'You are receiving this email because you are a member of the Public Group 311 Lucity Failure Notifications.\n\r Unable to update the cases given below due to errors. Please Find the Error Details Below\n';
            for(String str : M.KeySet()) {
                mailBody += 'Case Number : ' + str + '\n ERROR \n ' + M.get(str);
            }
           system.debug('Mail Body ' + mailBody);
           mail.setPlainTextBody(mailBody);                  
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
         }
         
  }  
    
   public List<String> getMailAddresses()
     {
                  List<String> mailList = new List<String>();
                  List<String> mailAddresses = new List<String>(); 
                  
                  Group g = [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = '311 Lucity Failure Notifications'];
                  for (GroupMember gm : g.groupMembers) 
                  {
                   mailList.add(gm.userOrGroupId);
                  }
                  User[] usr = [SELECT email FROM user WHERE id IN :mailList];
                  for(User u : usr) 
                  {
                  mailAddresses.add(u.email);
                  } 
                  return mailAddresses;
      } 
}
TestBatchSync class that is only covering 31% code coverage for the upon batchsync class
@isTest
public with sharing class TestBatchSync {

    static testmethod void m1() {

        List<Case> ca = new List<Case>();
        DateTime dt = System.now();
        for(integer i = 0; i<10; i++){
            Case c = new Case(Subject='testCase',Service_Request_Type__c = 'Alarms:  City Offices',Lucity_Returned_Date__c=dt,Lucity_Public_Works_Valid__c='yes',Lucity_WR_ID__c ='99999',status='New',Street_Number__c='230',Street_Name__c='Lincoln st'); 
            ca.add(c);
        }

        Test.StartTest();
        insert ca;
        BatchSync sync = new BatchSync();
        sync.query =  'Select Id,CaseNumber,status,Lucity_Public_Works__c,Lucity_Parks__c,Lucity_WR_ID__c from case where Lucity_WR_ID__c != NULL';
        ID batchprocessid = Database.executeBatch(sync);
        Test.StopTest();        
    }

}
Any assistance would be much appreciated.

Thanks,

 
Ashish_Sharma_DEVSFDCAshish_Sharma_DEVSFDC
Hi ,

Implement HTTPCalloutMock interfact to mimic your callout while test.
Refer this link for example https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_http_testing_httpcalloutmock.htm


Let us know if it helps.
Salesforce Admin2Salesforce Admin2
Thank you for the example.  I am still having trouble in implementing in my test script . I did create both the CalloutClass and the MockHttpResponseGenerator class.  I received the error Class.CalloutClass.getInfoFromExternalService: line 7, column 1 Class.TestBatchSyncfl.m1: line 23, column 1when I ran my TestBatchSyncFl (see below).  Line 23 is the HttpResponse res = CalloutClass.getInfoFromExternalService(); line.

@isTest
public with sharing class TestBatchSyncfl {
 
    static testmethod void m1() {
 
        List<Case> ca = new List<Case>();
        DateTime dt = System.now();
        for(integer i = 0; i<10; i++){
            Case c = new Case(Subject='testCase',Service_Request_Type__c = 'Alarms:  City Offices',Lucity_Returned_Date__c=dt,Lucity_Public_Works_Valid__c='yes',Lucity_WR_ID__c ='99999',status='New',Street_Number__c='230',Street_Name__c='Lincoln st');
            ca.add(c);
        }
 
        Test.StartTest();
        insert ca;
       
        //Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
       
        //Call method to test.
        //This causes a fake response to be sent
        //from the class that implements HttpCalloutMock
       
        HttpResponse res = CalloutClass.getInfoFromExternalService();
       
        //Verify response reeived contains fake values
        String contentType = res.getHeader('Content-Type');
       
        System.assert(contentType == 'application/json');
       
        String actualValue = res.getbody();
       
        String expectedValue = '{"foo":"bar"}';
            
        System.assertEquals(actualValue, expectedValue);
       
        System.assertEquals(200, res.getStatusCode());
 
        BatchSync sync = new BatchSync();
        sync.query =  'Select Id,CaseNumber,status,Lucity_Public_Works__c,Lucity_Parks__c,Lucity_WR_ID__c from case where Lucity_WR_ID__c != NULL';
        ID batchprocessid = Database.executeBatch(sync);
       
               
        Test.StopTest();       
    }
 
}