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

         }

}

This is the part of the code which I'm not able to cover​​​​​​​
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Tejashwini,

I hope you got some solution for this and also observed that this is duplicate question . Can you confirm if this coverage issue still exists.

Thanks,