function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Tejashwini S 1Tejashwini S 1 

I want to 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:
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)
    {
    }
}

 
AbhinavAbhinav (Salesforce Developers) 
Hi Tehjashwini,

Check this:

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

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

If you face any specific issue while attempting do post that here.

Thanks!
AnkaiahAnkaiah (Salesforce Developers) 
Hi Tejaswini,

Try with below code and modify the test data as per your need.
@isTest
private class BatchUpdateContactEmail_Test {

static testmethod void test() {


Account acc = new Account (Name = 'Account ',email='test@abc.com');

insert acc;


Contact[] conList = new List();
for (Integer i=0;i<200;i++) {
Contact m = new Contact(LastName = 'Account ' + i,FirstName='test',AccountId=acc.id);
conList.add(m);
}
insert conList;

//insert GenericEmailPattern__mdt test data

GenericEmailPattern__mdt metadata = new GenericEmailPattern__mdt();

metadata.Name = 'test';

insert metadata;

//insert EmailPattern__mdt test data
EmailPattern__mdt metadata2 = new EmailPattern__mdt();
metadata2.name ='test';
insert metadata2;

contact[] ConUpdatedList = [SELECT Id,Name,name FROM Contact where id=:conList];

for(contact con:ConUpdatedList ){
con.email = acc.email;

}

update ConUpdatedList;


Test.startTest();
BatchUpdateContactEmail c = new BatchUpdateContactEmail();
Database.executeBatch(c);
Test.stopTest();

}
}

If this helps, please mark it as best answer.
Tejashwini S 1Tejashwini S 1
Hi Ankaiah ,
This code is not working.