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 a help to write the test class

For the above Apex Batch Class I want to write the test class can anyone help with that.
Apex Class :
Global class BatchValidateEmailDominantPattern Implements Database.Batchable<sObject>,Database.AllowsCallouts{
    Global Database.QueryLocator Start(Database.BatchableContext BC){   
      /*  system.debug('Start!!!');
        String query = '';
        boolean noCredits = false;
        //Callout
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        //Checking credits
        String apiURL =  'https://api.zerobounce.net/v2/getcredits?api_key=831114db9d4a45b8b34e4944489d58c4';
        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';
                  }else{
                      noCredits = true;
                  }
              }
        }*/
        
        String accId = '001q000001Ll1puAAB';
        String query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null AND EmailBatchProcessed__c = true AND Id=:accId';
        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\":\"4b9d00ee45de4948a32ef302f01f1cec\", ';
                     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) {
            
        }
}
Best Answer chosen by Tejashwini S 1
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

The below piece of code gave me around 80% of code coverage.

Please replace the Account id with the account id in the batch. I kept the account id which is in my org.
 
@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='0015g00000OYhCxAAL');
        clist.add(c);
        contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample2@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c1);
        contact c2 = new contact(LastName='sample',MatchingEmail1__c='sample4@gmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c2);
        contact c3 = new contact(LastName='sample' ,MatchingEmail1__c='sample5@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c3);
        contact c4 = new contact(LastName='sample',MatchingEmail1__c='sample6@gmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c4);
        contact c5 = new contact(LastName='sample' ,MatchingEmail1__c='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',MatchingEmail1__c='sample@gmail.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 as best answer.

Thanks,

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi ,

is EmailValidationBatchJsonParser an another class? if so can you please help the community with that class as well.

Thanks,
 
Tejashwini S 1Tejashwini S 1
Hi Praveen,
Yeah EmailValidationBatchJsonParser is another class and here is the code:
public class EmailValidationBatchJsonParser {
    public list<String> errors{get;set;}
    public list<email_batch> email_batch{get;set;}
    public class email_batch{
        public String mx_record{get;set;}
        public String mx_found{get;set;}
        public String smtp_provider{get;set;}
        public String firstname{get;set;}
        public String domain_age_days{get;set;}
        public String lastname{get;set;}
        public String domain{get;set;}
        public String gender{get;set;}
        public String account{get;set;}
        public String country{get;set;}
        public String did_you_mean{get;set;}
        public String region{get;set;}
        public Boolean free_email{get;set;}
        public String city{get;set;}
        public String sub_status{get;set;}
        public String zipcode{get;set;}
        public String status{get;set;}
        public String processed_at{get;set;}
        public String address{get;set;}
    }
}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

The below piece of code gave me around 80% of code coverage.

Please replace the Account id with the account id in the batch. I kept the account id which is in my org.
 
@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='0015g00000OYhCxAAL');
        clist.add(c);
        contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample2@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c1);
        contact c2 = new contact(LastName='sample',MatchingEmail1__c='sample4@gmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c2);
        contact c3 = new contact(LastName='sample' ,MatchingEmail1__c='sample5@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c3);
        contact c4 = new contact(LastName='sample',MatchingEmail1__c='sample6@gmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c4);
        contact c5 = new contact(LastName='sample' ,MatchingEmail1__c='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',MatchingEmail1__c='sample@gmail.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 as best answer.

Thanks,
This was selected as the best answer
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

Are you using the same account id in the batch class and test class? make sure you use the same id and also the account should contain DominantEmailPattern__c field and EmailBatchProcessed__c as true.

Thanks,
 
Tejashwini S 1Tejashwini S 1
Hi 
Sai Praveen  ,

The coverage reached 78%.
Thank you so much...
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

Please mark the solution as best answer, If that helps you.

Thanks,