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 

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.
Best Answer chosen by Tejashwini S 1
AnkaiahAnkaiah (Salesforce Developers) 
Hi Tejaswani,

Try with below code and modify the test data as per your need.
@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.
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i,
                billingcity='Chennai', RoleProcessed__c='test',billingcountry='India'));
        }
        insert accounts;
        // find the account just inserted. add contact for each & test data required.
        for (Account account : [select id from account]) {
            contacts.add(new Contact(firstname='first',
                lastname='last',rdcc__Role__c='test', accountId=account.id));
        }
        insert contacts;
    }
    @isTest static void test() {
        Test.startTest();
        BatchUpdateContactRole Bucr = new BatchUpdateContactRole();
        Id batchId = Database.executeBatch(Bucr);
        Test.stopTest();

    }
}

If this helps, please mark it as best answer.

Thanks,
Ankaiah

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Tejashwini,

Can you provide the Apex code ?

Thanks,
Ankaiah 
Tejashwini S 1Tejashwini S 1
Hi Ankaiah,
Here is the code,

global class BatchUpdateContactRole implements Database.Batchable<sObject> 
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
            String query = 'SELECT Id, RoleProcessed__c, Name,(SELECT Id, rdcc__Role__c, FirstName, LastName FROM Contacts) FROM Account';
         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>();
         
             for(Account acc : scope){
                  boolean roleEmpty = false;
                  Integer countContact = 0;
                  String roleToUpdate = '';
                  Map<string,Integer> roleMap = new Map<string,Integer>();
                  if(acc.Id!=null && acc.RoleProcessed__c != true){
                          //countContact = acc.contacts.size();
              //       if(countContact > 1){
                          for(Contact cont : acc.contacts){
                              if(!roleEmpty){
                                  if(cont.rdcc__Role__c == null){
                                      //atleast one empty role is found within contacts of Account
                                      roleEmpty = true;
                                      system.debug('one role empty found');
                                      break;
                                  }    
                              }
                          }
                  //    }
                      if(roleEmpty){
                        Integer prevValue = 0;
                        Integer num = 1;
                          for(Contact cont : acc.contacts){
                           system.debug('contact to be processed, '+cont.Id+'account id '+acc.Id);
                            if(cont.rdcc__Role__c != null){
                                  //Put Roles in Map with its count
                                prevValue = roleMap.get(cont.rdcc__Role__c);
                                if(prevValue != null){
                                    num = prevValue + 1;
                                }else{
                                    num = 1;
                                }
                                roleMap.put(cont.rdcc__Role__c,num);
                            }
                         }
                          
                          List<Integer> mapValues =  new List<Integer>();
                          //Check the maximum count to find Dominant
                          Integer maxValue = 0;
                          Integer secondHighestValue = 0;
                          system.debug('roleMap'+roleMap);
                          if(roleMap.size() > 0){
                              mapValues = roleMap.values();
                              mapValues.sort();
                              maxValue = mapvalues[mapvalues.size()-1];
                              system.debug('maxValue'+maxValue);
                              if(mapValues.size()>1){
                                  secondHighestValue = mapvalues[mapValues.size()-2];
                              }
                              if(maxValue != secondHighestValue){ //dominant role not clashing
                                  for(String s : roleMap.keySet()){
                                      system.debug('s'+s);
                                      Integer pattern_value = roleMap.get(s);
                                      system.debug('pattern_value'+pattern_value);
                                      if((pattern_value == maxValue) && (maxValue > 0)){
                                          system.debug(' Dominant Role for contacts with accountId'+acc.Id+' is ' + s + ' with value' + pattern_value);
                                          roleToUpdate = s;
                                      }
                                  }
                              }
                          }
                          //Updating Role in contact with dominant role
                           for(Contact cont : acc.contacts){
                              // cont.MatchingRole__c = '';
                                   if(cont.rdcc__Role__c == null){
                                 system.debug('Role to update'+roleToUpdate);
                                     if(roleToUpdate != ''){
                                         cont.MatchingRole__c = roleToUpdate;
                                     }  
                                }
                              conToUpdate.add(cont);
                           }
                      }
                  }
                acc.RoleProcessed__c = true;        
                   accToUpdate.add(acc);
             }
              system.debug('Contact List........ '+conToUpdate);
             update conToUpdate;
              update accToUpdate;
        }catch(exception e){
                system.debug('e--'+e);
        }      
     }
    
    global void finish(Database.BatchableContext BC)
    {
    }
}
AnkaiahAnkaiah (Salesforce Developers) 
Hi Tejaswani,

Try with below code and modify the test data as per your need.
@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.
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i,
                billingcity='Chennai', RoleProcessed__c='test',billingcountry='India'));
        }
        insert accounts;
        // find the account just inserted. add contact for each & test data required.
        for (Account account : [select id from account]) {
            contacts.add(new Contact(firstname='first',
                lastname='last',rdcc__Role__c='test', accountId=account.id));
        }
        insert contacts;
    }
    @isTest static void test() {
        Test.startTest();
        BatchUpdateContactRole Bucr = new BatchUpdateContactRole();
        Id batchId = Database.executeBatch(Bucr);
        Test.stopTest();

    }
}

If this helps, please mark it as best answer.

Thanks,
Ankaiah
This was selected as the best answer
Tejashwini S 1Tejashwini S 1
It was really helpful,
Thank you so much.
Tejashwini S 1Tejashwini S 1
Hi 
Ankaiah ,
As per your code I code like this:

@isTest
private class TestBatchUpdateContactRoleClass {
    @testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
        List<Contact> contacts = new List<Contact>();
                
        // insert 200 accounts
        for (Integer i=0;i<200;i++) {
            
            accounts.add(new Account(name='Account '+i, 
                description ='Test', NumberOfEmployees=70));
        }
        insert accounts;
        // find the account just inserted. add contact for each
        for (Account account : [select id from account LIMIT 5]) {
            contacts.add(new Contact(firstname='first', 
                lastname='Test',rdcc__Role__c='', accountId=account.id));
        }
        insert contacts;
    }
        static testmethod void execute() {        
        Test.startTest();
        BatchUpdateContactRole tb = new BatchUpdateContactRole();
        Id batchId = Database.executeBatch(tb,50);
           Contact con = [Select Id from Contact Where rdcc__Role__c= null];
            con.rdcc__Role__c='';
            
               
        Test.stopTest();
            Integer cnt=[select count() from contact];
        // after the testing stops, assert records were inserted properly
        System.assertEquals(200, [select count() from contact]);
        System.assertEquals(200, [select count() from account]);
        }
}

This is the test class which as the 53per as the code coverage.
And this is the Scenerio which I have to achive by test class:
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.

CAN YOU PLZ HELP ME TO ACHIVE THE CODE COVERAGE OF 75%
 
AnkaiahAnkaiah (Salesforce Developers) 
@isTest
private class TestBatchUpdateContactRoleClass {
    @testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
        List<Contact> contacts = new List<Contact>();
                
        // insert 200 accounts
        for (Integer i=0;i<200;i++) {
            
            accounts.add(new Account(name='Account '+i, 
                description ='Test', NumberOfEmployees=70));
        }
        insert accounts;
        // find the account just inserted. add contact for each
        for (Account account : [select id from account LIMIT 5]) {
            contacts.add(new Contact(firstname='first', 
                lastname='Test',rdcc__Role__c='', accountId=account.id));
        }
        insert contacts;
    }
        static testmethod void execute() {        
        Test.startTest();
        BatchUpdateContactRole tb = new BatchUpdateContactRole();
        Id batchId = Database.executeBatch(tb,50);
           Contact con = [Select Id from Contact Where rdcc__Role__c= null];
            con.rdcc__Role__c='';
            
               
        Test.stopTest();
            Integer cnt=[select count() from contact];
        // after the testing stops, assert records were inserted properly
        System.assertEquals(200, [select count() from contact]);
        System.assertEquals(200, [select count() from account]);
        }
		
  static testmethod void execute1() { 
  
  List<contact> listcon = [select id,rdcc__Role__c from Contact ];
  for(contact con :listcon ){
    con.rdcc__Role__c = 'Dominant' ; // update the role
  }
  
  update listcon;
				
        Test.startTest();
        BatchUpdateContactRole tb = new BatchUpdateContactRole();
        Id batchId = Database.executeBatch(tb,50);
               
        Test.stopTest();
            Integer cnt=[select count() from contact];
        // after the testing stops, assert records were inserted properly
        System.assertEquals(200, [select count() from contact]);
        System.assertEquals(200, [select count() from account]);
        }
}

Add this code and try.
Tejashwini S 1Tejashwini S 1
The code coverage is again 53 percentage
Tejashwini S 1Tejashwini S 1
And even test run is getting fail
AnkaiahAnkaiah (Salesforce Developers) 
Can you provide the list of values in rdcc__Role__c field in contact. i will replicate in my org and get back to you.
Tejashwini S 1Tejashwini S 1

it can be anything like Architect, manager,
owner 
etc
AnkaiahAnkaiah (Salesforce Developers) 
Hi Tejaswini,

As per your code, test class will cover only one if condition. I have tried its increased upto 69%
@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.
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i,
                billingcity='Chennai',billingcountry='India'));
        }
        insert accounts;
        // find the account just inserted. add contact for each & test data required.
        for (Account account : [select id from account]) {
            contacts.add(new Contact(firstname='first',
                lastname='last',rdcc_Role__c='Test0', accountId=account.id));
        }
        insert contacts;
        
          List<contact> conlist = [select id,rdcc_Role__c from contact where id=:contacts];
        for(contact con :conlist )
        {
            con.rdcc_Role__c ='';
        }
        update conlist;

    }
 static testmethod void testMethod2(){        
      // system.test.startTest();
        BatchUpdateContactRole tb = new BatchUpdateContactRole();
        Id batchId = Database.executeBatch(tb,50);
            
               
      //system.test.stopTest();
        //    Integer cnt=[select count() from contact];
        // after the testing stops, assert records were inserted properly
        //System.assertEquals(200, [select count() from contact]);
       // System.assertEquals(200, [select count() from account]);
        }
}

 
Tejashwini S 1Tejashwini S 1
It covers 54 per
Aaron CorderoAaron Cordero
@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 tb = new BatchUpdateContactRole();
        Id batchId = Database.executeBatch(tb,50);
           //Test.stopTest();
         }
}

This code will cover 86%