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
Tejashwini S 1Tejashwini S 1 

I want to cover the code coverage of 75% in Apex Batch Class

Hi I have my code coverage of 12% while writing the apex class, can anyone help me to cover the code coverage of 75%.

Apex class
Global class BatchValidateEmailDominantPattern Implements Database.Batchable<sObject>,Database.AllowsCallouts, Database.stateful{
    Public boolean noCredit = false;
    Public string key;
    List<EmailValidationApiKey__mdt> apiKeys = [SELECT APIKey__c from EmailValidationApiKey__mdt];
    Global Database.QueryLocator Start(Database.BatchableContext BC){
        	system.debug('Start!!!');
            String query = '';
        try{
            //Callout
            HttpRequest req = new HttpRequest();
            HttpResponse res = new HttpResponse();
            Http http = new Http();
     		for(EmailValidationApiKey__mdt record: apiKeys){
               key = record.APIKey__c;
            }
            //Checking credits
            String apiURL =  'https://api.zerobounce.net/v2/getcredits?api_key='+key;
            req.setEndpoint(apiURL);
            req.setHeader('Content-Type', 'application/json');
            req.setMethod('GET');
            if (!Test.isRunningTest()) {
                  res = http.send(req);
                  system.debug('--res.getBody--'+res.getBody());
                  if(res.getStatusCode() == 200){
                      Map<String, Object> docData = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
                      system.debug('===docData==='+docData);
                      string credits =(string)docData.get('Credits');
                      Integer cred = Integer.valueOf(credits);
                      system.debug('credits'+cred);
                      if(cred >= 1){
                          system.debug('Credits'+cred);
                          query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null and EmailBatchProcessed__c = true limit 2';
                      }else{
                          string accid = '123';
                          query = 'Select Id,Name From Account where Id=:accid'; 
                          noCredit = true;
                          system.debug('Inside else');
                      }
                  }
            }
            
            /*String accId = '001q000001Ll1puAAB';
            String query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null AND EmailBatchProcessed__c = true AND Id=:accId';
            */
        }catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
        }
        return Database.getQueryLocator(query);
    }
    
    Global void execute(Database.BatchableContext BC, List<Account> scope) {
         system.debug('scope'+scope);
       	 String endpoint;
         Map<Id,String> DominantEmailContactMap = new Map<Id,String>();
		 List<String> ListemailList = new List<String>();
         List<List<String>> listWrapper =  new List<List<String>>();
         Set<string> allAccountIds = new set<string>();
         Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
         List<Contact> conToUpdate = new List<Contact>();
         List<Contact> allConToUpdate = new List<Contact>();
         Set<string> conIds = new set<string>();
         try { 
             if((scope.size() > 0)&& (scope!=null)){
                     for(Account a: scope){
                         allAccountIds.add(a.Id);
                     }
                     for(Contact con : [SELECT Id, Email, FirstName, LastName, MatchingEmail1__c, MatchingEmail2__c, accountId from Contact where accountId IN :allAccountIds and EmailValidateFlag__c = False]){
                         if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
                             AccountIdContactMap.get(con.accountId).add(con);
                         }else{
                             AccountIdContactMap.put(con.accountId, new list<contact>{con});              
                         }
                     }
                     for(string accId : AccountIdContactMap.keyset()){
                         if(accId!=null){
                             for(Contact cont : AccountIdContactMap.get(accId)){
                                 if(cont.MatchingEmail1__c != null)
                                 {   
                                     if( DominantEmailContactMap.containsKey(cont.Id))
                                     {
                                         String mapEmail = DominantEmailContactMap.get(cont.Id);
                                         mapEmail = cont.MatchingEmail1__c;
                                         DominantEmailContactMap.put(cont.Id,mapEmail);
                                     }else{                                    
                                         DominantEmailContactMap.put(cont.Id, cont.MatchingEmail1__c);
                                     }
                                 }
                             }
                         }
                     }	
                     if(DominantEmailContactMap!=null){
                         List<String> FinalEmailList = new List<String>();
                         ListemailList = DominantEmailContactMap.values();
                         for(String emailString : ListemailList )
                         {
                            FinalEmailList.add(emailString);
                         }
                         for(Integer i = 0 ; i < (FinalEmailList.size()/3)+1 ; i++){
                             List<String> lstTemp = new List<String>();
                             for(Integer j=(i*3);(j<(i*3)+3) && j<FinalEmailList.size() ; j++){
                                 lstTemp.add(FinalEmailList.get(j));
                             }
                              listWrapper.add(lstTemp);
                         }
                     }
                     system.debug('listWrapper'+listWrapper);
                     String firstPart = '{\"api_key\":\"'+key+', ';
                     String reqPart = '\"email_batch\":[';
                     for(List<String> emailTempList: listWrapper){
                         String emailRequest = '';
                   	     String matchingEmail = '';
                         if(emailTempList.size() == 1){
                             for(Integer i=0; i<emailTempList.size(); i++){
                                 matchingEmail = emailTempList[i];
                                 if(matchingEmail != ''){
                                    emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'}';
                                 }
                             }
                         }
                         else if(emailTempList.size()> 1){
                             for(Integer i=0; i<emailTempList.size(); i++){
                                 matchingEmail = emailTempList[i];
                                  if(matchingEmail != ''){
                                    emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'},';
                                  }
                               }
                         }
                         String lastPart = ']}';
                          if (emailRequest.right(1) == ',')
                            emailRequest = emailRequest.removeEnd(',');
                         String request = firstPart + reqPart + emailRequest +lastPart;
                         if(request != null)
                         {
                             HttpRequest req1 = new HttpRequest();
                             HttpResponse res1 = new HttpResponse();
                             Http http1 = new Http();
                             req1.setHeader('Content-Type',  'application/json');
                             req1.setEndpoint('https://bulkapi.zerobounce.net/v2/validatebatch');
                             req1.setMethod('POST');
                             req1.setBody(request);
                              if (!Test.isRunningTest()) {      
                                  res1 = http1.send(req1);
                                  System.debug('Response Validating email' + res1.getBody());
                                  if(res1.getStatusCode() == 200){
                                     system.debug('success');
                                     EmailValidationBatchJsonParser emailParserResponse = new EmailValidationBatchJsonParser();
                                     emailParserResponse = (EmailValidationBatchJsonParser) JSON.deserialize(res1.getBody(), EmailValidationBatchJsonParser.class);
                                     List<EmailValidationBatchJsonParser.email_batch> etList = emailParserResponse.email_batch;
                                     system.debug('list'+etList);  	
                                      for(EmailValidationBatchJsonParser.email_batch etObj : etList){
                                          if(etObj.status == 'Valid'){
                                              system.debug('Status Valid!!');
                                              for(Id conId : DominantEmailContactMap.keySet()){
                                                  if(DominantEmailContactMap.get(conId) == etObj.address){
                                                      system.debug('Email status valid for conId'+conId);
                                                       conIds.add(conId);
                                                  }
                                          	  }
                                          }else{
                                              system.debug('Not Valid status');
                                          }
                                      }
                                  }
                              }else{
                                  system.debug('status code: error');
                              }              
                         }          
                    }
                 	//Update Contacts Email
                     if(conIds!=null){
                         for(Contact con : [SELECT Id, Email, MatchingEmail1__c from Contact where Id IN:conIds]){
                             if(con.MatchingEmail1__c!=null){
                                 con.Email = con.MatchingEmail1__c;
                             }
                             conToUpdate.add(con);
                         }
                     }
                 	 for(Id conId : DominantEmailContactMap.keySet()){
                       	 Contact cn =  new Contact();
                         cn.Id = conId;
                         cn.EmailValidateFlag__c = True;
                         allConToUpdate.add(cn);
                     }
                     if(conToUpdate!=null && conToUpdate.size()>0){
                        update conToUpdate;
                     }
                 	if(allConToUpdate!=null && allConToUpdate.size()>0){
                        update allConToUpdate;
                     }
             	}
             }catch (Exception e) {         
                 System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
             }
        }
        Global void finish(Database.BatchableContext BC) {
            system.debug('Inside finish'+noCredit);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'shweta.lal@nagarro.com'};
            mail.setToAddresses(toAddresses);
            if(nocredit){
        	    mail.setSubject('No Credits Found!');
                mail.setPlainTextBody('Credits are not available on this API key');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }else{
                AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =: BC.getJobId()];
                mail.setSubject('Dominant Email Pattern Batch ' + a.Status);
                mail.setPlainTextBody('records processed ' + a.TotalJobItems + 'with '+ a.NumberOfErrors + ' failures.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
}

Test Class
@isTest(SeeAllData=true)
public class TestBatchValidate {
    @istest
    public static void testmet(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample',MatchingEmail1__c='sample@gmail.com' ,Accountid='001q000001OLBBwAAP');
        clist.add(c);
        contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample2@gmail.com',Accountid='001q000001OLBBwAAP');
        clist.add(c1);
        contact c2 = new contact(LastName='sample',MatchingEmail1__c='sample4@gmail.com' ,Accountid='001q000001OLBBwAAP');
        clist.add(c2);
        contact c3 = new contact(LastName='sample' ,MatchingEmail1__c='sample5@gmail.com',Accountid='001q000001OLBBwAAP');
        clist.add(c3);
        contact c4 = new contact(LastName='sample',MatchingEmail1__c='sample6@gmail.com' ,Accountid='001q000001OLBBwAAP');
        clist.add(c4);
        contact c5 = new contact(LastName='sample' ,MatchingEmail1__c='sample7@gmail.com',Accountid='001q000001OLBBwAAP');
        clist.add(c5);
        
        insert(clist);

         Test.startTest();

            BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
    
        @istest
    public static void testmet2(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample',MatchingEmail1__c='sample@gmail.com' ,Accountid='001q000001OLBB3AAP');
        clist.add(c);
        
        insert(clist);

         Test.startTest();

            BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }

}

​​​​​​​
Best Answer chosen by Tejashwini S 1
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

It is not a best pratice to use test.isRunningTest() while calling a webservice as these cannot be covered while writing the test classes. Please find the below article for the same.

https://salesforce.stackexchange.com/questions/87680/test-isrunningtest-how-do-we-write-test-class-to-cover-this

But if you want to still go with this you can update the main class as below 
 
Global class BatchValidateEmailDominantPattern Implements Database.Batchable<sObject>,Database.AllowsCallouts, Database.stateful{
    Public boolean noCredit = false;
    Public string key;
    List<EmailValidationApiKey__mdt> apiKeys = [SELECT APIKey__c from EmailValidationApiKey__mdt];
    Global Database.QueryLocator Start(Database.BatchableContext BC){
        	system.debug('Start!!!');
            String query = '';
        try{
            //Callout
            HttpRequest req = new HttpRequest();
            HttpResponse res = new HttpResponse();
            Http http = new Http();
     		for(EmailValidationApiKey__mdt record: apiKeys){
               key = record.APIKey__c;
            }
            //Checking credits
            String apiURL =  'https://api.zerobounce.net/v2/getcredits?api_key='+key;
            req.setEndpoint(apiURL);
            req.setHeader('Content-Type', 'application/json');
            req.setMethod('GET');
            if (!Test.isRunningTest()) {
                  res = http.send(req);
                  system.debug('--res.getBody--'+res.getBody());
                  if(res.getStatusCode() == 200){
                      Map<String, Object> docData = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
                      system.debug('===docData==='+docData);
                      string credits =(string)docData.get('Credits');
                      Integer cred = Integer.valueOf(credits);
                      system.debug('credits'+cred);
                      if(cred >= 1){
                          system.debug('Credits'+cred);
                          query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null and EmailBatchProcessed__c = true limit 2';
                      }else{
                          string accid = '123';
                          query = 'Select Id,Name From Account where Id=:accid'; 
                          noCredit = true;
                          system.debug('Inside else');
                      }
                  }
            }
            else{
                query='select id,name  FROM Account where id=\'0015g00000OYhCxAAL\'';
            }
            
            /*String accId = '001q000001Ll1puAAB';
            String query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null AND EmailBatchProcessed__c = true AND Id=:accId';
            */
        }catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
        }
        return Database.getQueryLocator(query);
    }
    
    Global void execute(Database.BatchableContext BC, List<Account> scope) {
         system.debug('scope'+scope);
       	 String endpoint;
         Map<Id,String> DominantEmailContactMap = new Map<Id,String>();
		 List<String> ListemailList = new List<String>();
         List<List<String>> listWrapper =  new List<List<String>>();
         Set<string> allAccountIds = new set<string>();
         Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
         List<Contact> conToUpdate = new List<Contact>();
         List<Contact> allConToUpdate = new List<Contact>();
         Set<string> conIds = new set<string>();
         try { 
             if((scope.size() > 0)&& (scope!=null)){
                     for(Account a: scope){
                         allAccountIds.add(a.Id);
                     }
                     for(Contact con : [SELECT Id, Email, FirstName, LastName, MatchingEmail1__c, MatchingEmail2__c, accountId from Contact where accountId IN :allAccountIds and EmailValidateFlag__c = False]){
                         if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
                             AccountIdContactMap.get(con.accountId).add(con);
                         }else{
                             AccountIdContactMap.put(con.accountId, new list<contact>{con});              
                         }
                     }
                     for(string accId : AccountIdContactMap.keyset()){
                         if(accId!=null){
                             for(Contact cont : AccountIdContactMap.get(accId)){
                                 if(cont.MatchingEmail1__c != null)
                                 {   
                                     if( DominantEmailContactMap.containsKey(cont.Id))
                                     {
                                         String mapEmail = DominantEmailContactMap.get(cont.Id);
                                         mapEmail = cont.MatchingEmail1__c;
                                         DominantEmailContactMap.put(cont.Id,mapEmail);
                                     }else{                                    
                                         DominantEmailContactMap.put(cont.Id, cont.MatchingEmail1__c);
                                     }
                                 }
                             }
                         }
                     }	
                     if(DominantEmailContactMap!=null){
                         List<String> FinalEmailList = new List<String>();
                         ListemailList = DominantEmailContactMap.values();
                         for(String emailString : ListemailList )
                         {
                            FinalEmailList.add(emailString);
                         }
                         for(Integer i = 0 ; i < (FinalEmailList.size()/3)+1 ; i++){
                             List<String> lstTemp = new List<String>();
                             for(Integer j=(i*3);(j<(i*3)+3) && j<FinalEmailList.size() ; j++){
                                 lstTemp.add(FinalEmailList.get(j));
                             }
                              listWrapper.add(lstTemp);
                         }
                     }
                     system.debug('listWrapper'+listWrapper);
                     String firstPart = '{\"api_key\":\"'+key+', ';
                     String reqPart = '\"email_batch\":[';
                     for(List<String> emailTempList: listWrapper){
                         String emailRequest = '';
                   	     String matchingEmail = '';
                         if(emailTempList.size() == 1){
                             for(Integer i=0; i<emailTempList.size(); i++){
                                 matchingEmail = emailTempList[i];
                                 if(matchingEmail != ''){
                                    emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'}';
                                 }
                             }
                         }
                         else if(emailTempList.size()> 1){
                             for(Integer i=0; i<emailTempList.size(); i++){
                                 matchingEmail = emailTempList[i];
                                  if(matchingEmail != ''){
                                    emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'},';
                                  }
                               }
                         }
                         String lastPart = ']}';
                          if (emailRequest.right(1) == ',')
                            emailRequest = emailRequest.removeEnd(',');
                         String request = firstPart + reqPart + emailRequest +lastPart;
                         if(request != null)
                         {
                             HttpRequest req1 = new HttpRequest();
                             HttpResponse res1 = new HttpResponse();
                             Http http1 = new Http();
                             req1.setHeader('Content-Type',  'application/json');
                             req1.setEndpoint('https://bulkapi.zerobounce.net/v2/validatebatch');
                             req1.setMethod('POST');
                             req1.setBody(request);
                              if (!Test.isRunningTest()) {      
                                  res1 = http1.send(req1);
                                  System.debug('Response Validating email' + res1.getBody());
                                  if(res1.getStatusCode() == 200){
                                     system.debug('success');
                                     EmailValidationBatchJsonParser emailParserResponse = new EmailValidationBatchJsonParser();
                                     emailParserResponse = (EmailValidationBatchJsonParser) JSON.deserialize(res1.getBody(), EmailValidationBatchJsonParser.class);
                                     List<EmailValidationBatchJsonParser.email_batch> etList = emailParserResponse.email_batch;
                                     system.debug('list'+etList);  	
                                      for(EmailValidationBatchJsonParser.email_batch etObj : etList){
                                          if(etObj.status == 'Valid'){
                                              system.debug('Status Valid!!');
                                              for(Id conId : DominantEmailContactMap.keySet()){
                                                  if(DominantEmailContactMap.get(conId) == etObj.address){
                                                      system.debug('Email status valid for conId'+conId);
                                                       conIds.add(conId);
                                                  }
                                          	  }
                                          }else{
                                              system.debug('Not Valid status');
                                          }
                                      }
                                  }
                              }else{
                                  system.debug('status code: error');
                              }              
                         }          
                    }
                 	//Update Contacts Email
                     if(conIds!=null){
                         for(Contact con : [SELECT Id, Email, MatchingEmail1__c from Contact where Id IN:conIds]){
                             if(con.MatchingEmail1__c!=null){
                                 con.Email = con.MatchingEmail1__c;
                             }
                             conToUpdate.add(con);
                         }
                     }
                 	 for(Id conId : DominantEmailContactMap.keySet()){
                       	 Contact cn =  new Contact();
                         cn.Id = conId;
                         cn.EmailValidateFlag__c = True;
                         allConToUpdate.add(cn);
                     }
                     if(conToUpdate!=null && conToUpdate.size()>0){
                        update conToUpdate;
                     }
                 	if(allConToUpdate!=null && allConToUpdate.size()>0){
                        update allConToUpdate;
                     }
             	}
             }catch (Exception e) {         
                 System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
             }
        }
        Global void finish(Database.BatchableContext BC) {
            system.debug('Inside finish'+noCredit);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'shweta.lal@nagarro.com'};
            mail.setToAddresses(toAddresses);
            if(nocredit){
        	    mail.setSubject('No Credits Found!');
                mail.setPlainTextBody('Credits are not available on this API key');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }else{
                AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =: BC.getJobId()];
                mail.setSubject('Dominant Email Pattern Batch ' + a.Status);
                mail.setPlainTextBody('records processed ' + a.TotalJobItems + 'with '+ a.NumberOfErrors + ' failures.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
}

I just hardcoded the value if that is from test class so we get atleast one record into the execute method. But this is not good pratice.

If this solution helps, Please mark it as best answer.

Thanks,

 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

The below test class covers around 76%. Please use the Accountid from your org.
 
@isTest(SeeAllData=true)
public class TestBatchValidate {
    @istest
    public static void testmet(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample name',Accountid='0015g00000OYhCxAAL');
        clist.add(c);
        contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample@gah.com',FirstName='sample',Accountid='0015g00000OYhCxAAL');
        clist.add(c1);
        contact c2 = new contact(LastName='sample',Accountid='0015g00000OYhCxAAL');
        clist.add(c2);
        contact c3 = new contact(LastName='sample' ,email='sample5@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c3);
        contact c4 = new contact(LastName='sample',email='sample6@gmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c4);
        contact c5 = new contact(LastName='sample' ,email='sample7@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c5);
        
        insert(clist);

         Test.startTest();

            BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
    
        @istest
    public static void testmet2(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample name',email='sample@gdsdmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c);
        
        insert(clist);

         Test.startTest();

            BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }

}
If this solution helps, Please mark it as best answer.

Thanks,

 
Tejashwini S 1Tejashwini S 1
I have given the account id which is in my org
Sai PraveenSai Praveen (Salesforce Developers) 
Does this resolve your issue?
 
Tejashwini S 1Tejashwini S 1
No it didnt.The code coverage is still 12%
Tejashwini S 1Tejashwini S 1
Even after I changed the account id to my org account id
Sai PraveenSai Praveen (Salesforce Developers) 
Can you please show the apex code where it is not covering so i can suggest you more on it.
 
Tejashwini S 1Tejashwini S 1
User-added image
Tejashwini S 1Tejashwini S 1
User-added imageUser-added image
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

Can you check if the account id which you are using satifies the below criteria. As these are the conditions for the batch to pick the record.
 
DominantEmailPattern__c != null AND EmailBatchProcessed__c = true

Thanks,
 
Tejashwini S 1Tejashwini S 1
yeah it is satisfying
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

If the account which you are using in the text class and main class are satisfying the conditions and both should be same then it should enter into execute methos. But it is not even entering into execute method.

Make sure the account id you used in test class is same as in the batch and the other condition which i mentioend above. 

Thanks,
 
Tejashwini S 1Tejashwini S 1
Hi Sai Praveen
There is no id in apex class, as it is commented.
 
Tejashwini S 1Tejashwini S 1
Shall I resend the apex code again?
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

It is not a best pratice to use test.isRunningTest() while calling a webservice as these cannot be covered while writing the test classes. Please find the below article for the same.

https://salesforce.stackexchange.com/questions/87680/test-isrunningtest-how-do-we-write-test-class-to-cover-this

But if you want to still go with this you can update the main class as below 
 
Global class BatchValidateEmailDominantPattern Implements Database.Batchable<sObject>,Database.AllowsCallouts, Database.stateful{
    Public boolean noCredit = false;
    Public string key;
    List<EmailValidationApiKey__mdt> apiKeys = [SELECT APIKey__c from EmailValidationApiKey__mdt];
    Global Database.QueryLocator Start(Database.BatchableContext BC){
        	system.debug('Start!!!');
            String query = '';
        try{
            //Callout
            HttpRequest req = new HttpRequest();
            HttpResponse res = new HttpResponse();
            Http http = new Http();
     		for(EmailValidationApiKey__mdt record: apiKeys){
               key = record.APIKey__c;
            }
            //Checking credits
            String apiURL =  'https://api.zerobounce.net/v2/getcredits?api_key='+key;
            req.setEndpoint(apiURL);
            req.setHeader('Content-Type', 'application/json');
            req.setMethod('GET');
            if (!Test.isRunningTest()) {
                  res = http.send(req);
                  system.debug('--res.getBody--'+res.getBody());
                  if(res.getStatusCode() == 200){
                      Map<String, Object> docData = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
                      system.debug('===docData==='+docData);
                      string credits =(string)docData.get('Credits');
                      Integer cred = Integer.valueOf(credits);
                      system.debug('credits'+cred);
                      if(cred >= 1){
                          system.debug('Credits'+cred);
                          query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null and EmailBatchProcessed__c = true limit 2';
                      }else{
                          string accid = '123';
                          query = 'Select Id,Name From Account where Id=:accid'; 
                          noCredit = true;
                          system.debug('Inside else');
                      }
                  }
            }
            else{
                query='select id,name  FROM Account where id=\'0015g00000OYhCxAAL\'';
            }
            
            /*String accId = '001q000001Ll1puAAB';
            String query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null AND EmailBatchProcessed__c = true AND Id=:accId';
            */
        }catch (Exception e) {         
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
        }
        return Database.getQueryLocator(query);
    }
    
    Global void execute(Database.BatchableContext BC, List<Account> scope) {
         system.debug('scope'+scope);
       	 String endpoint;
         Map<Id,String> DominantEmailContactMap = new Map<Id,String>();
		 List<String> ListemailList = new List<String>();
         List<List<String>> listWrapper =  new List<List<String>>();
         Set<string> allAccountIds = new set<string>();
         Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>();
         List<Contact> conToUpdate = new List<Contact>();
         List<Contact> allConToUpdate = new List<Contact>();
         Set<string> conIds = new set<string>();
         try { 
             if((scope.size() > 0)&& (scope!=null)){
                     for(Account a: scope){
                         allAccountIds.add(a.Id);
                     }
                     for(Contact con : [SELECT Id, Email, FirstName, LastName, MatchingEmail1__c, MatchingEmail2__c, accountId from Contact where accountId IN :allAccountIds and EmailValidateFlag__c = False]){
                         if(AccountIdContactMap.containsKey(con.accountId) && AccountIdContactMap.get(con.accountId)!=null){
                             AccountIdContactMap.get(con.accountId).add(con);
                         }else{
                             AccountIdContactMap.put(con.accountId, new list<contact>{con});              
                         }
                     }
                     for(string accId : AccountIdContactMap.keyset()){
                         if(accId!=null){
                             for(Contact cont : AccountIdContactMap.get(accId)){
                                 if(cont.MatchingEmail1__c != null)
                                 {   
                                     if( DominantEmailContactMap.containsKey(cont.Id))
                                     {
                                         String mapEmail = DominantEmailContactMap.get(cont.Id);
                                         mapEmail = cont.MatchingEmail1__c;
                                         DominantEmailContactMap.put(cont.Id,mapEmail);
                                     }else{                                    
                                         DominantEmailContactMap.put(cont.Id, cont.MatchingEmail1__c);
                                     }
                                 }
                             }
                         }
                     }	
                     if(DominantEmailContactMap!=null){
                         List<String> FinalEmailList = new List<String>();
                         ListemailList = DominantEmailContactMap.values();
                         for(String emailString : ListemailList )
                         {
                            FinalEmailList.add(emailString);
                         }
                         for(Integer i = 0 ; i < (FinalEmailList.size()/3)+1 ; i++){
                             List<String> lstTemp = new List<String>();
                             for(Integer j=(i*3);(j<(i*3)+3) && j<FinalEmailList.size() ; j++){
                                 lstTemp.add(FinalEmailList.get(j));
                             }
                              listWrapper.add(lstTemp);
                         }
                     }
                     system.debug('listWrapper'+listWrapper);
                     String firstPart = '{\"api_key\":\"'+key+', ';
                     String reqPart = '\"email_batch\":[';
                     for(List<String> emailTempList: listWrapper){
                         String emailRequest = '';
                   	     String matchingEmail = '';
                         if(emailTempList.size() == 1){
                             for(Integer i=0; i<emailTempList.size(); i++){
                                 matchingEmail = emailTempList[i];
                                 if(matchingEmail != ''){
                                    emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'}';
                                 }
                             }
                         }
                         else if(emailTempList.size()> 1){
                             for(Integer i=0; i<emailTempList.size(); i++){
                                 matchingEmail = emailTempList[i];
                                  if(matchingEmail != ''){
                                    emailRequest += '{\"email_address\": '+'\"'+matchingEmail+'\"'+'},';
                                  }
                               }
                         }
                         String lastPart = ']}';
                          if (emailRequest.right(1) == ',')
                            emailRequest = emailRequest.removeEnd(',');
                         String request = firstPart + reqPart + emailRequest +lastPart;
                         if(request != null)
                         {
                             HttpRequest req1 = new HttpRequest();
                             HttpResponse res1 = new HttpResponse();
                             Http http1 = new Http();
                             req1.setHeader('Content-Type',  'application/json');
                             req1.setEndpoint('https://bulkapi.zerobounce.net/v2/validatebatch');
                             req1.setMethod('POST');
                             req1.setBody(request);
                              if (!Test.isRunningTest()) {      
                                  res1 = http1.send(req1);
                                  System.debug('Response Validating email' + res1.getBody());
                                  if(res1.getStatusCode() == 200){
                                     system.debug('success');
                                     EmailValidationBatchJsonParser emailParserResponse = new EmailValidationBatchJsonParser();
                                     emailParserResponse = (EmailValidationBatchJsonParser) JSON.deserialize(res1.getBody(), EmailValidationBatchJsonParser.class);
                                     List<EmailValidationBatchJsonParser.email_batch> etList = emailParserResponse.email_batch;
                                     system.debug('list'+etList);  	
                                      for(EmailValidationBatchJsonParser.email_batch etObj : etList){
                                          if(etObj.status == 'Valid'){
                                              system.debug('Status Valid!!');
                                              for(Id conId : DominantEmailContactMap.keySet()){
                                                  if(DominantEmailContactMap.get(conId) == etObj.address){
                                                      system.debug('Email status valid for conId'+conId);
                                                       conIds.add(conId);
                                                  }
                                          	  }
                                          }else{
                                              system.debug('Not Valid status');
                                          }
                                      }
                                  }
                              }else{
                                  system.debug('status code: error');
                              }              
                         }          
                    }
                 	//Update Contacts Email
                     if(conIds!=null){
                         for(Contact con : [SELECT Id, Email, MatchingEmail1__c from Contact where Id IN:conIds]){
                             if(con.MatchingEmail1__c!=null){
                                 con.Email = con.MatchingEmail1__c;
                             }
                             conToUpdate.add(con);
                         }
                     }
                 	 for(Id conId : DominantEmailContactMap.keySet()){
                       	 Contact cn =  new Contact();
                         cn.Id = conId;
                         cn.EmailValidateFlag__c = True;
                         allConToUpdate.add(cn);
                     }
                     if(conToUpdate!=null && conToUpdate.size()>0){
                        update conToUpdate;
                     }
                 	if(allConToUpdate!=null && allConToUpdate.size()>0){
                        update allConToUpdate;
                     }
             	}
             }catch (Exception e) {         
                 System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
             }
        }
        Global void finish(Database.BatchableContext BC) {
            system.debug('Inside finish'+noCredit);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'shweta.lal@nagarro.com'};
            mail.setToAddresses(toAddresses);
            if(nocredit){
        	    mail.setSubject('No Credits Found!');
                mail.setPlainTextBody('Credits are not available on this API key');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }else{
                AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors,JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =: BC.getJobId()];
                mail.setSubject('Dominant Email Pattern Batch ' + a.Status);
                mail.setPlainTextBody('records processed ' + a.TotalJobItems + 'with '+ a.NumberOfErrors + ' failures.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
        }
}

I just hardcoded the value if that is from test class so we get atleast one record into the execute method. But this is not good pratice.

If this solution helps, Please mark it as best answer.

Thanks,

 
This was selected as the best answer
Tejashwini S 1Tejashwini S 1
Thank you
Tejashwini S 1Tejashwini S 1
Hi,
The following test class is covering the code of 18%.
@isTest(SeeAllData=true)
public class TestBatchValidate {
    @istest
    public static void testmet(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample name',Accountid='001q000001Ll1puAAB');
        clist.add(c);
        contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample@gah.com',FirstName='sample',Accountid='001q000001Ll1puAAB');
        clist.add(c1);
        contact c2 = new contact(LastName='sample',Accountid='001q000001Ll1puAAB');
        clist.add(c2);
        contact c3 = new contact(LastName='sample' ,email='sample5@gmail.com',Accountid='001q000001Ll1puAAB');
        clist.add(c3);
        contact c4 = new contact(LastName='sample',email='sample6@gmail.com' ,Accountid='001q000001Ll1puAAB');
        clist.add(c4);
        contact c5 = new contact(LastName='sample' ,email='sample7@gmail.com',Accountid='001q000001Ll1puAAB');
        clist.add(c5);
        
        insert(clist);

         Test.startTest();

            BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
    
        @istest
    public static void testmet2(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample name',email='sample@gdsdmail.com' ,Accountid='001q000001Ll1puAAB');
        clist.add(c);
        
        insert(clist);

         Test.startTest();

            BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }

}