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
Aqua MatrixAqua Matrix 

I want a help to cover code coverage for below apex class

Hi,
I have code coverage of 44% for below apex batch class,help me in covering code coverage of 75% for below Apex class.
Apex code:
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){

         String query = '';

         Set<String> accIds = new Set<String>();

         //accIds.add('001q000001OZhiPAAT');

         //accIds.add('001q000001Ll1puAAB');

         //accIds.add('001q000001OJZxpAAH');

         //accIds.add('001q000001Ll1puAAB');

        try{

            system.debug('Validate Email Pattern start!');

            //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');

            String defaultAcc = 'Test Email';

            if (!Test.isRunningTest()) {

                  res = http.send(req);

                  system.debug('--res.getBody--'+res.getBody());

                  if(res.getStatusCode() == 200){

                        system.debug('success status');

                      Map<String, Object> docData = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());

                      string credits =(string)docData.get('Credits');

                      Integer cred = Integer.valueOf(credits);

                      if(cred >= 1){

                          system.debug('Credits'+cred);

                          query = 'SELECT Id, Name FROM Account where DominantEmailPattern__c != null and EmailBatchProcessed__c = true AND ID IN :accIds';

                      }else{

                          query = 'Select Id,Name From Account where Name =: defaultAcc';

                          noCredit = true;

                      }

                  }

            }else{

                query='Select Id,Name From Account where Name =: defaultAcc';

            }

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

         Set<string> catchAllConIds = new set<string>();

         try {

             if((scope.size() > 0)&& (scope!=null)){

                     system.debug('scope size greater than 0');

                     for(Account a: scope){

                         allAccountIds.add(a.Id);

                     }

                     system.debug('allAccountIds'+allAccountIds);

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

                         }

                     }

                     system.debug('AccountIdcontactmap'+AccountIdContactMap);

                     for(string accId : AccountIdContactMap.keyset()){

                         system.debug('Inside loop');

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

                                     }

                                 }

                             }

                         }

                     }         

                     system.debug('DominantEmailContactMap'+DominantEmailContactMap);

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

                             }

                            if(lstTemp!=null && lstTemp.size()>0){

                                  listWrapper.add(lstTemp);

                             }

                         }

                     }

                     String firstPart = '{\"api_key\":\"'+key+'\",';

                     String reqPart = '\"email_batch\":[';

                       system.debug('listwrapper'+listWrapper);

                     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;

                         system.debug('Request'+request);

                         if(request != null)

                         {

                             system.debug('Inside if');

                             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){

                                     EmailValidationBatchJsonParser emailParserResponse = new EmailValidationBatchJsonParser();

                                     emailParserResponse = (EmailValidationBatchJsonParser) JSON.deserialize(res1.getBody(), EmailValidationBatchJsonParser.class);

                                     List<EmailValidationBatchJsonParser.email_batch> etList = emailParserResponse.email_batch;

                                      for(EmailValidationBatchJsonParser.email_batch etObj : etList){

                                          system.debug('etObj.status'+etObj.status);

                                          if(etObj.status == 'Valid'){

                                              system.debug('Email Status Valid');

                                              for(Id conId : DominantEmailContactMap.keySet()){

                                                  if(DominantEmailContactMap.get(conId) == etObj.address){

                                                       conIds.add(conId);

                                                  }

                                              }

                                          }else if(etObj.status == 'catch-all'){

                                              for(Id conId : DominantEmailContactMap.keySet()){

                                                  if(DominantEmailContactMap.get(conId) == etObj.address){

                                                       catchAllConIds.add(conId);

                                                  }

                                              }

                                          }else{

                                              system.debug('Not Valid status');

                                          }

                                      }

                                  }else{

                                      system.debug('Response Failure!!');

                                  }

                              }else{

                                  system.debug('status code: error');

                              }             

                         }         

                    }

                      //Update Contacts Email

                      system.debug('conIds'+conIds);

                     if(conIds!=null){

                         system.debug('Inside');

                         for(Contact con : [SELECT Id, Email, MatchingEmail1__c from Contact where Id IN:conIds]){

                             if(con.MatchingEmail1__c!=null){

                                 system.debug('con'+con.Id);

                                 con.ValidEmail__c = con.MatchingEmail1__c;

                                 system.debug('con updated email'+con.ValidEmail__c);

                             }

                             conToUpdate.add(con);

                         }

                     }

                     if(catchAllConIds!=null){

                         for(Contact cont: [SELECT Id, catchAllEmail__c from Contact where Id IN:catchAllConIds]){

                              cont.catchAllEmail__c = True;

                              conToUpdate.add(cont);

                         }   

                      }

                       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) {

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

            String[] toAddresses = new String[] {'shweta.lal@nagarro.com','aditya.pandey@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>();

        List<Account> accounts = new List<Account>();

        Account acc=new Account(name='Account ',SecDomEmailPattern__c  = 'FinitialLastName@va.gov',

                billingcity='Chennai',billingcountry='India',EmailBatchProcessed__c = true,DominantEmailPattern__c='FirstName.LastName@aec.com',RoleProcessed__c=True);

            accounts.add(acc);

       

        contact c = new contact(LastName='sample name',MatchingEmail1__c='samplename@gmail.com',Accountid=acc.Id);

        clist.add(c);

        contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample@gah.com',FirstName='sample',Accountid=acc.Id);

        clist.add(c1);

        contact c2 = new contact(LastName='sample',MatchingEmail1__c='',Accountid=acc.Id);

        clist.add(c2);

        contact c3 = new contact(LastName='sample' ,MatchingEmail1__c='sample5@gmail.com',Accountid=acc.Id);

        clist.add(c3);

        contact c4 = new contact(LastName='sample',MatchingEmail1__c='sample6@gmail.com' ,Accountid=acc.Id);

        clist.add(c4);

        contact c5 = new contact(LastName='sample' ,MatchingEmail1__c='sample7@gmail.com',Accountid=acc.Id);

        clist.add(c5);

       

        insert(clist);

 

 

    }

   

        @istest

    public static void testmet2(){

         Test.startTest();

 

            BatchValidateEmailDominantPattern obj = new BatchValidateEmailDominantPattern();

            DataBase.executeBatch(obj);

            

        Test.stopTest();

    }

 

}


 
Suraj Tripathi 47Suraj Tripathi 47
Hi Aqua Matrix ,
Please share code-coverage Screenshot of your Class, after that Community will helps you.
Thank you!
Regards,
Suraj Tripathi
Aqua MatrixAqua Matrix
Hi suraj,here is the screenshot which has code coverage of 44% and code which has not covered.User-added imageUser-added image
AbhinavAbhinav (Salesforce Developers) 
Check this

https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines

https://salesforce.stackexchange.com/questions/244788/how-do-i-write-an-apex-unit-test

Thanks!