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

i want to write a test class for below apex batch class

hii,
i want to write a test class for below apex batch class which covers 75% code coverage.
Apex code:
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)

    {

    }

}


 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi ,

Please find the below test class which is covering 52%. We are not able to cover more because the apex class is failing with null pointer exception. Null checks were not made properly.

For example : In case of map null check you should use 
 
if(!emailDomainMap.isEmpty() && emailDomainMap!=null){
For field null check please use the below.
 
if(cont.FirstName != '' && !String.isBlank(cont.FirstName))


 
@isTest(SeeAllData=true)
public class TestBatchValidate {
    @istest
    public static void testmet(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample name', FirstName='sample' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c);
        contact c1 = new contact(LastName='sample' ,MatchingEmail1__c='sample@gah.com',FirstName='sample',Accountid='0015g00000OYhCxAAL');
        clist.add(c1);a
        //contact c2 = new contact(LastName='sample',Accountid='0015g00000OYhCxAAL');
       // clist.add(c2);
        contact c3 = new contact(LastName='sample' ,FirstName='sample',email='sample5@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c3);
        contact c4 = new contact(LastName='sample',FirstName='sample',email='sample6@gmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c4);
        contact c5 = new contact(LastName='sample' ,FirstName='sample',email='sample7@gmail.com',Accountid='0015g00000OYhCxAAL');
        clist.add(c5);
        
        insert(clist);

         Test.startTest();

            BatchUpdateContactEmail obj = new BatchUpdateContactEmail();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }
    
        @istest
    public static void testmet2(){
        List<Contact> clist = new List<Contact>();
        
        contact c = new contact(LastName='sample name',FirstName='sample',email='sample@gdsdmail.com' ,Accountid='0015g00000OYhCxAAL');
        clist.add(c);
        
        insert(clist);

         Test.startTest();

            BatchUpdateContactEmail obj = new BatchUpdateContactEmail();
            DataBase.executeBatch(obj); 
            
        Test.stopTest();
    }

}

If this solution helps, Please mark it as best answer.

Thanks,

 
Aqua MatrixAqua Matrix
Hi praveen,
Iam getting following error please help me solve this error:
User-added image
Sai PraveenSai Praveen (Salesforce Developers) 
Hi ,

Can you please check if the class name is unique. You will get this error if there is another class with same name.

Thanks,
 
Aqua MatrixAqua Matrix
Hi,Code coverage of 1per with above code,Can you help me to cover the code coverage of ,75.