-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
8Questions
-
22Replies
update the Contact owner and Account owner with the user who created the Case, How to do this
update the Contact owner and Account owner with the user who created the Case, How to do this
- Tejashwini S 1
- November 10, 2021
- Like
- 0
I want to cover the code coverage of 80% in Apex Batch Class
Hi ,
I have the code coverageof 57% in below apex code and could you plz help me to cover the code upto 80%...
Apex code:
Test Class:
I have the code coverageof 57% in below apex code and could you plz help me to cover the code upto 80%...
Apex code:
global class BatchUpdateContactRole implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext BC) { String str = '001q000001Ob8yxAAB'; String query = 'SELECT Id, RoleProcessed__c, Name FROM Account Where id =:str'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Account> scope) { try{ List<Contact> conToUpdate = new List<Contact>(); List<Account> accToUpdate = new List<Account>(); Set<string> allAccountIds = new set<string>(); Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>(); Map<Id,Account> AccountData = new Map<Id,Account>(); Map<String, DominantRolePatternm__mdt> mapEd = DominantRolePatternm__mdt.getAll(); for(Account a: scope){ allAccountIds.add(a.Id); AccountData.put(a.id,a); } system.debug('All AccountIds'+allAccountIds); for(Contact con : [SELECT Id, rdcc__Role__c, FirstName, LastName, accountId from Contact where accountId IN :allAccountIds]){ 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()){ boolean roleEmpty = false; boolean allroleEmpty = false; Integer countContact = 0; Integer countNull = 0; String roleToUpdate = ''; Map<string,Integer> roleMap = new Map<string,Integer>(); if(accId!=null){ system.debug('account Id'+accId); for(Contact cont : AccountIdContactMap.get(accId)){ system.debug('Contact to be processed'+cont.Id); if(cont.rdcc__Role__c == null){ //atleast one empty role is found within contacts of Account roleEmpty = true; ++countNull; system.debug('empty role found'); //break; } // system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull); if(countNull == AccountIdContactMap.get(accId).size()) { allroleEmpty = true; } } system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull); if(roleEmpty && allroleEmpty) { Account AccData = AccountData.get(accId); for(String nameEmailDomain : mapEd.keySet()){ System.debug('----->'+mapEd.get(nameEmailDomain).Name_Combination__c); List<String> lsttest= mapEd.get(nameEmailDomain).Name_Combination__c.split(';'); for(String roleStr : lsttest) { system.debug('inside contains111--'+roleStr); if(AccData.Name.contains(roleStr)) { system.debug('inside contains222-'+roleStr); for(Contact cont : AccountIdContactMap.get(accId)){ cont.MatchingRole__c = mapEd.get(nameEmailDomain).RoleMatched__c; conToUpdate.add(cont); } } } } } else if(roleEmpty && !allroleEmpty) { system.debug('Inside If Condition'); Integer prevValue = 0; Integer num = 1; for(Contact cont : AccountIdContactMap.get(accId)){ system.debug('Contact to be processed'+cont.Id); if(cont.rdcc__Role__c != null){ system.debug('roleMap'+roleMap); if(roleMap.containsKey(cont.rdcc__Role__c)){ num = roleMap.get(cont.rdcc__Role__c); roleMap.put(cont.rdcc__Role__c,num+1); }else{ roleMap.put(cont.rdcc__Role__c,num); } } } system.debug('Role Map'+roleMap); List<Integer> mapValues = new List<Integer>(); //Check the maximum count to find Dominant Integer maxValue = 0; Integer secondHighestValue = 0; if(roleMap.size() > 0){ mapValues = roleMap.values(); mapValues.sort(); maxValue = mapvalues[mapvalues.size()-1]; if(mapValues.size()>1){ secondHighestValue = mapvalues[mapValues.size()-2]; } system.debug('max Values'+maxValue); system.debug('second highest value'+secondHighestValue); if(maxValue != secondHighestValue){ //dominant role not clashing for(String s : roleMap.keySet()){ Integer pattern_value = roleMap.get(s); if((pattern_value == maxValue) && (maxValue > 0)){ system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value); roleToUpdate = s; } } } else if(maxValue == secondHighestValue){ //dominant role not clashing for(String s : roleMap.keySet()){ system.debug('s'+s); Integer pattern_value = roleMap.get(s); if((pattern_value == maxValue) && (maxValue > 0) ||(pattern_value == secondHighestValue) && (secondHighestValue > 0) ){ system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value); for (String St : System.Label.Significant_Role.split(',')) { if(st.equalsIgnoreCase(s)) roleToUpdate = s; } } } } } system.debug('AccountIdContactMap'+AccountIdContactMap); //Updating Role in contact with dominant role for(Contact cont : AccountIdContactMap.get(accId)){ if(cont.rdcc__Role__c == null){ system.debug('roleToUpdate'+roleToUpdate); if(roleToUpdate != ''){ cont.MatchingRole__c = roleToUpdate; cont.rdcc__Role__c = roleToUpdate; } } conToUpdate.add(cont); } } } //acc.RoleProcessed__c = true; Account acc = new Account(); acc.Id = accId; acc.RoleProcessed__c = True; accToUpdate.add(acc); } system.debug('Con To Update'+conToUpdate); if(conToUpdate.size()>0 && conToUpdate!=null){ update conToUpdate; } system.debug('Acc To Update'+accToUpdate); if(accToUpdate.size()>0 && accToUpdate!=null){ update accToUpdate; } }catch(exception e){ system.debug('e--'+e); } } global void finish(Database.BatchableContext BC) { } }
Test Class:
@isTest(seealldata=true) private class BatchUpdateContactRoleTest { static void setup() { List<Account> accounts = new List<Account>(); List<Contact> contacts = new List<Contact>(); List<Integer> mapValues = new List<Integer>(); // insert 10 accounts and add test fields as per your need. Account acc=new Account(name='Account ', billingcity='Chennai',billingcountry='India'); insert acc; // find the account just inserted. add contact for each & test data required. Contact con1=new Contact(firstname='first', lastname='last',rdcc__Role__c='Test0',email='firstlast@gmail.com', accountId=acc.id); insert con1; Contact con2=new Contact(firstname='first', lastname='last',rdcc__Role__c='Test1',email='first.last@gmail.com', accountId=acc.id); insert con2; Contact con3=new Contact(firstname='first', lastname='last',rdcc__Role__c='',email='first123last@gmail.com', accountId=acc.id); insert con3; Contact con4=new Contact(firstname='first', lastname='last',email='', accountId=acc.id); insert con4; } static testmethod void testMethod2(){ Test.startTest(); BatchUpdateContactRole tb = new BatchUpdateContactRole(); Id batchId = Database.executeBatch(tb,50); Test.stopTest(); } }
- Tejashwini S 1
- October 29, 2021
- Like
- 0
Help for covering the test class code coverage.
Hi,
I have a test class that has a code coverage of 5% and it's not covering the execute method. So can anyone plz help me in identifying the error and make the code coverage 80%
Apex class:
Test class:
I have a test class that has a code coverage of 5% and it's not covering the execute method. So can anyone plz help me in identifying the error and make the code coverage 80%
Apex class:
global class BatchUpdateContactRole implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext BC) { String str = '001q000001Ob8yxAAB'; String query = 'SELECT Id, RoleProcessed__c, Name FROM Account Where id =:str'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Account> scope) { try{ List<Contact> conToUpdate = new List<Contact>(); List<Account> accToUpdate = new List<Account>(); Set<string> allAccountIds = new set<string>(); Map<string, list<Contact>> AccountIdContactMap = new Map<string, list<Contact>>(); Map<Id,Account> AccountData = new Map<Id,Account>(); Map<String, DominantRolePatternm__mdt> mapEd = DominantRolePatternm__mdt.getAll(); for(Account a: scope){ allAccountIds.add(a.Id); AccountData.put(a.id,a); } system.debug('All AccountIds'+allAccountIds); for(Contact con : [SELECT Id, rdcc__Role__c, FirstName, LastName, accountId from Contact where accountId IN :allAccountIds]){ 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()){ boolean roleEmpty = false; boolean allroleEmpty = false; Integer countContact = 0; Integer countNull = 0; String roleToUpdate = ''; Map<string,Integer> roleMap = new Map<string,Integer>(); if(accId!=null){ system.debug('account Id'+accId); for(Contact cont : AccountIdContactMap.get(accId)){ system.debug('Contact to be processed'+cont.Id); if(cont.rdcc__Role__c == null){ //atleast one empty role is found within contacts of Account roleEmpty = true; ++countNull; system.debug('empty role found'); //break; } // system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull); if(countNull == AccountIdContactMap.get(accId).size()) { allroleEmpty = true; } } system.debug('sizeee--'+AccountIdContactMap.get(accId).size()+'--- count--'+countNull); if(roleEmpty && allroleEmpty) { Account AccData = AccountData.get(accId); for(String nameEmailDomain : mapEd.keySet()){ System.debug('----->'+mapEd.get(nameEmailDomain).Name_Combination__c); List<String> lsttest= mapEd.get(nameEmailDomain).Name_Combination__c.split(';'); for(String roleStr : lsttest) { system.debug('inside contains111--'+roleStr); if(AccData.Name.contains(roleStr)) { system.debug('inside contains222-'+roleStr); for(Contact cont : AccountIdContactMap.get(accId)){ cont.MatchingRole__c = mapEd.get(nameEmailDomain).RoleMatched__c; conToUpdate.add(cont); } } } } } else if(roleEmpty && !allroleEmpty) { system.debug('Inside If Condition'); Integer prevValue = 0; Integer num = 1; for(Contact cont : AccountIdContactMap.get(accId)){ system.debug('Contact to be processed'+cont.Id); if(cont.rdcc__Role__c != null){ system.debug('roleMap'+roleMap); if(roleMap.containsKey(cont.rdcc__Role__c)){ num = roleMap.get(cont.rdcc__Role__c); roleMap.put(cont.rdcc__Role__c,num+1); }else{ roleMap.put(cont.rdcc__Role__c,num); } } } system.debug('Role Map'+roleMap); List<Integer> mapValues = new List<Integer>(); //Check the maximum count to find Dominant Integer maxValue = 0; Integer secondHighestValue = 0; if(roleMap.size() > 0){ mapValues = roleMap.values(); mapValues.sort(); maxValue = mapvalues[mapvalues.size()-1]; if(mapValues.size()>1){ secondHighestValue = mapvalues[mapValues.size()-2]; } system.debug('max Values'+maxValue); system.debug('second highest value'+secondHighestValue); if(maxValue != secondHighestValue){ //dominant role not clashing for(String s : roleMap.keySet()){ Integer pattern_value = roleMap.get(s); if((pattern_value == maxValue) && (maxValue > 0)){ system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value); roleToUpdate = s; } } } else if(maxValue == secondHighestValue){ //dominant role not clashing for(String s : roleMap.keySet()){ system.debug('s'+s); Integer pattern_value = roleMap.get(s); if((pattern_value == maxValue) && (maxValue > 0) ||(pattern_value == secondHighestValue) && (secondHighestValue > 0) ){ system.debug(' Dominant Role for contacts with accountId'+accId+' is ' + s + ' with value' + pattern_value); for (String St : System.Label.Significant_Role.split(',')) { if(st.equalsIgnoreCase(s)) roleToUpdate = s; } } } } } system.debug('AccountIdContactMap'+AccountIdContactMap); //Updating Role in contact with dominant role for(Contact cont : AccountIdContactMap.get(accId)){ if(cont.rdcc__Role__c == null){ system.debug('roleToUpdate'+roleToUpdate); if(roleToUpdate != ''){ cont.MatchingRole__c = roleToUpdate; cont.rdcc__Role__c = roleToUpdate; } } conToUpdate.add(cont); } } } //acc.RoleProcessed__c = true; Account acc = new Account(); acc.Id = accId; acc.RoleProcessed__c = True; accToUpdate.add(acc); } system.debug('Con To Update'+conToUpdate); if(conToUpdate.size()>0 && conToUpdate!=null){ update conToUpdate; } system.debug('Acc To Update'+accToUpdate); if(accToUpdate.size()>0 && accToUpdate!=null){ update accToUpdate; } }catch(exception e){ system.debug('e--'+e); } } global void finish(Database.BatchableContext BC) { } }
Test class:
@isTest private class BatchUpdateContactRoleTest { @testSetup static void setup() { List<Account> accounts = new List<Account>(); List<Contact> contacts = new List<Contact>(); // insert 10 accounts and add test fields as per your need. Account acc=new Account(name='Account ', billingcity='Chennai',billingcountry='India'); insert acc; // find the account just inserted. add contact for each & test data required. Contact con1=new Contact(firstname='first', lastname='last',rdcc__Role__c='Test0', accountId=acc.id); insert con1; Contact con2=new Contact(firstname='first', lastname='last',rdcc__Role__c='Test1', accountId=acc.id); insert con2; Contact con3=new Contact(firstname='first', lastname='last',rdcc__Role__c='', accountId=acc.id); insert con3; } static testmethod void testMethod2(){ test.startTest(); BatchUpdateContactRole tb1 = new BatchUpdateContactRole(); Id batchId = Database.executeBatch(tb1,50); test.stopTest(); } }
- Tejashwini S 1
- October 28, 2021
- Like
- 0
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(); } }
- Tejashwini S 1
- September 13, 2021
- Like
- 0
I want to write test class for Apex class
Hi,
Can anyone help us to write the test class for below apex class with the 75% code coverage.
Apex Class:
Can anyone help us to write the test class for below apex class with the 75% code coverage.
Apex Class:
global class BatchUpdateContactEmail implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext BC) { String accId = '001q000001Ll27sAAB'; String query = 'SELECT Id,EmailBatchProcessed__c, Name,(SELECT Id, Email, FirstName, LastName FROM Contacts) FROM Account Where Id =: accId'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Account> scope) { try{ system.debug('scope'+scope); List<Contact> conToUpdate = new List<Contact>(); List<Account> accToUpdate = new List<Account>(); List<String> patternList = new List <String>(); List<String> genericPattern = new List<String>(); List<EmailPattern__mdt> listEmailPattern = [SELECT Id, Pattern__c from EmailPattern__mdt]; List<GenericEmailPattern__mdt> genericPatternList = [SELECT Id, GenericPattern__c from GenericEmailPattern__mdt]; for(EmailPattern__mdt record: listEmailPattern){ patternList.add(record.Pattern__c); } for(GenericEmailPattern__mdt record: genericPatternList){ genericPattern.add(record.GenericPattern__c); } for(Account acc : scope){ Map<string,Integer> counterMap = new Map<string,Integer>(); Map<Id,string> emailConMap = new Map<Id,string>(); Map<Id,string> accountDomainMap = new Map<Id,string>(); Map<string,Integer> emailDomainMap = new Map<string,Integer>(); boolean emailEmpty = false; Integer countContact = 0; String dominantPattern = ''; String secondDominantPattern = ''; String maxDomain = ''; for(string s1:patternList){ counterMap.put(s1,0); } if(acc.Id!=null && acc.EmailBatchProcessed__c!=true){ countContact = acc.contacts.size(); if(countContact > 1){ for(Contact cont : acc.contacts) { if(emailEmpty == false){ if(cont.Email == null){ system.debug('one empty email found'); //atleast one empty email is found within contacts of Account emailEmpty = true; break; } } } } //if atleast one blank email found if(emailEmpty == true){ Integer domainCount = 0; boolean validDomain = false; String domainName = ''; Map<string,integer> emailMap = new Map<string,integer>(); boolean noMatch = false; boolean patternFound = false; for(Contact cont : acc.contacts){ system.debug('contact to be processed'+cont.Id); Map<string,string> conMap = new Map<string,string>(); String temps = ''; String emailDomain = ''; Integer num = 0; if(cont.Email !=null && cont.Email!=''){ temps = cont.Email.split('@')[0]; emailDomain = cont.Email.split('@')[1]; Integer prevValue = 0; boolean validEmail = true; boolean genericPatternFound = false; system.debug('genericPattern List'+genericPattern); for(String s: genericPattern){ if(cont.Email.contains(s)){ genericPatternFound=true; break; } } //Finding Maximum repeated Domain if(!genericPatternFound){ system.debug('Not generic pattern'); if(emailDomain != ''){ prevValue = emailDomainMap.get(emailDomain); if(prevValue != null){ num = num + 1; } emailDomainMap.put(emailDomain,num); } string firstName = ''; string lastName = ''; if(cont.FirstName != ''){ firstName = cont.FirstName.toLowercase(); } if(cont.LastName != ''){ lastName = cont.LastName.toLowercase(); String middleName = ''; if (lastName.containsWhitespace()){ List<String> names = lastName.split(''); for(String name :names){ middleName = names.get(0); } } } system.debug('firstname'+firstName); system.debug('lastname'+lastName); conMap.put(firstName+'.'+lastName,'FirstName.LastName'); conMap.put(firstName,'FirstName'); conMap.put(firstName+lastName,'FirstNameLastName'); conMap.put(firstName.substring(0,1)+lastName,'FinitialLastName'); conMap.put(firstName+lastName.substring(0,1),'FirstNameLastinitial'); conMap.put(firstName.substring(0,1)+'.'+lastName,'Finitial.LastName'); conMap.put(firstName+'_'+lastName,'FirstName_LastName'); conMap.put(firstName+'-'+lastName,'FirstName-LastName'); conMap.put(firstName.substring(0,1)+'_'+lastName,'Finitial_LastName'); //replace it with temps system.debug('temps'+temps); string pattern = conMap.get(temps); system.debug('conMap'+conMap); system.debug('Pattern'+pattern); if(pattern != null) { if(patternFound!= true){ patternFound = true; } integer count = counterMap.get(pattern); count = count + 1; counterMap.put(pattern,count); }else{ noMatch = true; } } } } //Check the maximum count to find Dominant pattern in an Account if(patternFound){ Integer maxValue = 0; Integer secondHighestValue = 0; List<Integer> mapValues = new List<Integer>(); List<String> patternKeyList = new List<String>(); if(counterMap != null){ mapValues = counterMap.values(); mapValues.sort(); maxValue = mapvalues[mapvalues.size()-1]; secondHighestValue = mapvalues[mapValues.size()-2]; string secondPartEmail = ''; boolean dominantPatternFound = false; for(String s : counterMap.keySet()) { Integer pattern_value = counterMap.get(s); if((pattern_value == maxValue) && (maxValue > 0)) { if(!dominantPatternFound){ system.debug(' Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value); dominantPattern = s; dominantPatternFound = true; } } if((pattern_value == secondHighestValue) && (secondHighestValue > 0)){ system.debug(' Second Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value); secondDominantPattern = s; } } } //Checking Max Domain Name Integer highestNum = 0; List<Integer> domainList = new List<Integer>(); if(emailDomainMap != null){ domainList = emailDomainMap.values(); domainList.sort(); if(domainList.size()>0){ highestNum = domainList[domainList.size()-1]; } } for(String domain : emailDomainMap.keySet()){ Integer num = emailDomainMap.get(domain); if(num == highestNum){ maxDomain = domain; system.debug('Max Domain for contacts with accountId'+acc.Id+' is ' + maxDomain); } } //Updating fields in contact with pattern formed email for(Contact cont : acc.contacts){ // cont.MatchingEmail1__c = ''; // cont.MatchingEmail2__c = ''; string patternString = ''; string emailDomain = ''; List<String> domPatternList = new List<String>(); domPatternList.add(dominantPattern); domPatternList.add(secondDominantPattern); if(cont.Email == null){ cont.MatchingEmail1__c = ''; cont.MatchingEmail2__c = ''; string firstName = ''; string lastName = ''; string middleName = ''; if(cont.FirstName != null && cont.FirstName != ''){ firstName = cont.FirstName.toLowercase(); } if(cont.LastName != null && cont.LastName != ''){ lastName = cont.LastName.toLowercase(); List<String> names = new List<string>(); if (lastName.containsWhitespace()){ names = lastName.split(''); }else if(lastName.contains('.')){ names = lastName.split('.'); } for(String name :names){ middleName = names.get(0); } } if(middleName != ''){ lastName = middleName; } for(string s2:domPatternList){ switch on s2{ when 'FirstName.LastName' { patternString = firstName+'.'+lastName; }when 'FirstName' { patternString = firstName; }when 'FirstNameLastName' { patternString = firstName+lastName; }when 'FinitialLastName' { patternString = firstName.substring(0,1)+lastName; }when 'FirstNameLastinitial' { patternString = firstName+lastName.substring(0,1); }when 'Finitial.LastName' { patternString = firstName.substring(0,1)+'.'+lastName; }when 'FirstName_LastName' { patternString = firstName+'_'+lastName; }when 'FirstName-LastName' { patternString = firstName+'-'+lastName; }when 'Finitial_LastName' { patternString = firstName.substring(0,1)+'_'+lastName; }when else{ system.debug('No Match found'); } } if(s2.equals(dominantPattern)){ if(dominantPattern != ''){ cont.MatchingEmail1__c = patternString+'@'+maxDomain; } }else if (s2.equals(secondDominantPattern)){ if(secondDominantPattern != ''){ cont.MatchingEmail2__c = patternString+'@'+maxDomain; } } } } conToUpdate.add(cont); } } } } acc.EmailBatchProcessed__c = true; if(dominantPattern != ''){ acc.DominantEmailPattern__c = dominantPattern+'@'+maxDomain; } accToUpdate.add(acc); } system.debug('Contact List........ '+conToUpdate); if(conToUpdate.size()>0 && conToUpdate!=null){ update conToUpdate; } if(accToUpdate.size()>0 && accToUpdate!=null){ update accToUpdate; } }catch(exception e){ system.debug('e--'+e); } } global void finish(Database.BatchableContext BC) { } }
- Tejashwini S 1
- September 09, 2021
- Like
- 0
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) {
}
}
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) {
}
}
- Tejashwini S 1
- September 08, 2021
- Like
- 0
whether a duplicate rule can be created on lead to find out if the email on lead matches with any contact's email
Whether a duplicate rule can be created on lead to find out if the email on lead matches with any contact's email????
- Tejashwini S 1
- September 08, 2021
- Like
- 0
Can you plz help me to write test case for above scenerio?? The need help to write test class for batch apex
Insert empty roles in contacts on basis of highest matching role in accounts.( Automation and Manual)
- Dominant roles in a contact related to account will be filled in empty roles.
- In Case of single contact in a account, which has empty roles , it will be left empty.
- In Case of there is a tie in dominant pattern , empty role will be left blank.
- Tejashwini S 1
- August 27, 2021
- Like
- 0
I want help in writing trigger.
Hi,
I had created data in the custom metadata for city and zipcode...
I want to write the apex trigger to autopopulate the cityname If I select the zipcode which s present in the custom metadata...
Could you please help me to write the trigger for the above scenario...
I had written the apex code to fetch the custom metadata
And now I want to write the trigger to autopopulate the city name if we choose the zipcode.
I had created data in the custom metadata for city and zipcode...
I want to write the apex trigger to autopopulate the cityname If I select the zipcode which s present in the custom metadata...
Could you please help me to write the trigger for the above scenario...
I had written the apex code to fetch the custom metadata
And now I want to write the trigger to autopopulate the city name if we choose the zipcode.
trigger Autopopulate on Contact (after insert) { // When a new account is created, fill in the city and state based on zip code if (trigger.isAfter && trigger.isInsert) { zipcodemetda.fetchAllMetadata(); } }
- Aqua Matrix
- October 19, 2021
- Like
- 0
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(); } }
- Tejashwini S 1
- September 13, 2021
- Like
- 0
I want to write test class for Apex class
Hi,
Can anyone help us to write the test class for below apex class with the 75% code coverage.
Apex Class:
Can anyone help us to write the test class for below apex class with the 75% code coverage.
Apex Class:
global class BatchUpdateContactEmail implements Database.Batchable<sObject> { global Database.QueryLocator start(Database.BatchableContext BC) { String accId = '001q000001Ll27sAAB'; String query = 'SELECT Id,EmailBatchProcessed__c, Name,(SELECT Id, Email, FirstName, LastName FROM Contacts) FROM Account Where Id =: accId'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Account> scope) { try{ system.debug('scope'+scope); List<Contact> conToUpdate = new List<Contact>(); List<Account> accToUpdate = new List<Account>(); List<String> patternList = new List <String>(); List<String> genericPattern = new List<String>(); List<EmailPattern__mdt> listEmailPattern = [SELECT Id, Pattern__c from EmailPattern__mdt]; List<GenericEmailPattern__mdt> genericPatternList = [SELECT Id, GenericPattern__c from GenericEmailPattern__mdt]; for(EmailPattern__mdt record: listEmailPattern){ patternList.add(record.Pattern__c); } for(GenericEmailPattern__mdt record: genericPatternList){ genericPattern.add(record.GenericPattern__c); } for(Account acc : scope){ Map<string,Integer> counterMap = new Map<string,Integer>(); Map<Id,string> emailConMap = new Map<Id,string>(); Map<Id,string> accountDomainMap = new Map<Id,string>(); Map<string,Integer> emailDomainMap = new Map<string,Integer>(); boolean emailEmpty = false; Integer countContact = 0; String dominantPattern = ''; String secondDominantPattern = ''; String maxDomain = ''; for(string s1:patternList){ counterMap.put(s1,0); } if(acc.Id!=null && acc.EmailBatchProcessed__c!=true){ countContact = acc.contacts.size(); if(countContact > 1){ for(Contact cont : acc.contacts) { if(emailEmpty == false){ if(cont.Email == null){ system.debug('one empty email found'); //atleast one empty email is found within contacts of Account emailEmpty = true; break; } } } } //if atleast one blank email found if(emailEmpty == true){ Integer domainCount = 0; boolean validDomain = false; String domainName = ''; Map<string,integer> emailMap = new Map<string,integer>(); boolean noMatch = false; boolean patternFound = false; for(Contact cont : acc.contacts){ system.debug('contact to be processed'+cont.Id); Map<string,string> conMap = new Map<string,string>(); String temps = ''; String emailDomain = ''; Integer num = 0; if(cont.Email !=null && cont.Email!=''){ temps = cont.Email.split('@')[0]; emailDomain = cont.Email.split('@')[1]; Integer prevValue = 0; boolean validEmail = true; boolean genericPatternFound = false; system.debug('genericPattern List'+genericPattern); for(String s: genericPattern){ if(cont.Email.contains(s)){ genericPatternFound=true; break; } } //Finding Maximum repeated Domain if(!genericPatternFound){ system.debug('Not generic pattern'); if(emailDomain != ''){ prevValue = emailDomainMap.get(emailDomain); if(prevValue != null){ num = num + 1; } emailDomainMap.put(emailDomain,num); } string firstName = ''; string lastName = ''; if(cont.FirstName != ''){ firstName = cont.FirstName.toLowercase(); } if(cont.LastName != ''){ lastName = cont.LastName.toLowercase(); String middleName = ''; if (lastName.containsWhitespace()){ List<String> names = lastName.split(''); for(String name :names){ middleName = names.get(0); } } } system.debug('firstname'+firstName); system.debug('lastname'+lastName); conMap.put(firstName+'.'+lastName,'FirstName.LastName'); conMap.put(firstName,'FirstName'); conMap.put(firstName+lastName,'FirstNameLastName'); conMap.put(firstName.substring(0,1)+lastName,'FinitialLastName'); conMap.put(firstName+lastName.substring(0,1),'FirstNameLastinitial'); conMap.put(firstName.substring(0,1)+'.'+lastName,'Finitial.LastName'); conMap.put(firstName+'_'+lastName,'FirstName_LastName'); conMap.put(firstName+'-'+lastName,'FirstName-LastName'); conMap.put(firstName.substring(0,1)+'_'+lastName,'Finitial_LastName'); //replace it with temps system.debug('temps'+temps); string pattern = conMap.get(temps); system.debug('conMap'+conMap); system.debug('Pattern'+pattern); if(pattern != null) { if(patternFound!= true){ patternFound = true; } integer count = counterMap.get(pattern); count = count + 1; counterMap.put(pattern,count); }else{ noMatch = true; } } } } //Check the maximum count to find Dominant pattern in an Account if(patternFound){ Integer maxValue = 0; Integer secondHighestValue = 0; List<Integer> mapValues = new List<Integer>(); List<String> patternKeyList = new List<String>(); if(counterMap != null){ mapValues = counterMap.values(); mapValues.sort(); maxValue = mapvalues[mapvalues.size()-1]; secondHighestValue = mapvalues[mapValues.size()-2]; string secondPartEmail = ''; boolean dominantPatternFound = false; for(String s : counterMap.keySet()) { Integer pattern_value = counterMap.get(s); if((pattern_value == maxValue) && (maxValue > 0)) { if(!dominantPatternFound){ system.debug(' Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value); dominantPattern = s; dominantPatternFound = true; } } if((pattern_value == secondHighestValue) && (secondHighestValue > 0)){ system.debug(' Second Dominant Pattern Email for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value); secondDominantPattern = s; } } } //Checking Max Domain Name Integer highestNum = 0; List<Integer> domainList = new List<Integer>(); if(emailDomainMap != null){ domainList = emailDomainMap.values(); domainList.sort(); if(domainList.size()>0){ highestNum = domainList[domainList.size()-1]; } } for(String domain : emailDomainMap.keySet()){ Integer num = emailDomainMap.get(domain); if(num == highestNum){ maxDomain = domain; system.debug('Max Domain for contacts with accountId'+acc.Id+' is ' + maxDomain); } } //Updating fields in contact with pattern formed email for(Contact cont : acc.contacts){ // cont.MatchingEmail1__c = ''; // cont.MatchingEmail2__c = ''; string patternString = ''; string emailDomain = ''; List<String> domPatternList = new List<String>(); domPatternList.add(dominantPattern); domPatternList.add(secondDominantPattern); if(cont.Email == null){ cont.MatchingEmail1__c = ''; cont.MatchingEmail2__c = ''; string firstName = ''; string lastName = ''; string middleName = ''; if(cont.FirstName != null && cont.FirstName != ''){ firstName = cont.FirstName.toLowercase(); } if(cont.LastName != null && cont.LastName != ''){ lastName = cont.LastName.toLowercase(); List<String> names = new List<string>(); if (lastName.containsWhitespace()){ names = lastName.split(''); }else if(lastName.contains('.')){ names = lastName.split('.'); } for(String name :names){ middleName = names.get(0); } } if(middleName != ''){ lastName = middleName; } for(string s2:domPatternList){ switch on s2{ when 'FirstName.LastName' { patternString = firstName+'.'+lastName; }when 'FirstName' { patternString = firstName; }when 'FirstNameLastName' { patternString = firstName+lastName; }when 'FinitialLastName' { patternString = firstName.substring(0,1)+lastName; }when 'FirstNameLastinitial' { patternString = firstName+lastName.substring(0,1); }when 'Finitial.LastName' { patternString = firstName.substring(0,1)+'.'+lastName; }when 'FirstName_LastName' { patternString = firstName+'_'+lastName; }when 'FirstName-LastName' { patternString = firstName+'-'+lastName; }when 'Finitial_LastName' { patternString = firstName.substring(0,1)+'_'+lastName; }when else{ system.debug('No Match found'); } } if(s2.equals(dominantPattern)){ if(dominantPattern != ''){ cont.MatchingEmail1__c = patternString+'@'+maxDomain; } }else if (s2.equals(secondDominantPattern)){ if(secondDominantPattern != ''){ cont.MatchingEmail2__c = patternString+'@'+maxDomain; } } } } conToUpdate.add(cont); } } } } acc.EmailBatchProcessed__c = true; if(dominantPattern != ''){ acc.DominantEmailPattern__c = dominantPattern+'@'+maxDomain; } accToUpdate.add(acc); } system.debug('Contact List........ '+conToUpdate); if(conToUpdate.size()>0 && conToUpdate!=null){ update conToUpdate; } if(accToUpdate.size()>0 && accToUpdate!=null){ update accToUpdate; } }catch(exception e){ system.debug('e--'+e); } } global void finish(Database.BatchableContext BC) { } }
- Tejashwini S 1
- September 09, 2021
- Like
- 0
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) {
}
}
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) {
}
}
- Tejashwini S 1
- September 08, 2021
- Like
- 0
whether a duplicate rule can be created on lead to find out if the email on lead matches with any contact's email
Whether a duplicate rule can be created on lead to find out if the email on lead matches with any contact's email????
- Tejashwini S 1
- September 08, 2021
- Like
- 0
Can you plz help me to write test case for above scenerio?? The need help to write test class for batch apex
Insert empty roles in contacts on basis of highest matching role in accounts.( Automation and Manual)
- Dominant roles in a contact related to account will be filled in empty roles.
- In Case of single contact in a account, which has empty roles , it will be left empty.
- In Case of there is a tie in dominant pattern , empty role will be left blank.
- Tejashwini S 1
- August 27, 2021
- Like
- 0