You need to sign in to do that
Don't have an account?
Tejashwini 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
Test Class
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(); } }
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
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
The below test class covers around 76%. Please use the Accountid from your org.
If this solution helps, Please mark it as best answer.
Thanks,
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.
Thanks,
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,
There is no id in apex class, as it is commented.
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
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,
The following test class is covering the code of 18%.