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
Gwirizanani SinoiaGwirizanani Sinoia 

Batch job test class

Hi everyone,

I am currently getting 68% test coverage. Please help!

global class MatchingAddBatch Implements Schedulable, Database.Batchable<sObject>,Database.Stateful{
    Double failedUpdates;
    Id customerRecordType;
    global void execute(SchedulableContext sc) {
        Database.executeBatch(this);
    }
    
    global database.queryLocator start(Database.BatchableContext BC) { 
        customerRecordType = Schema.SObjectType.Account.RecordTypeInfosByName.get('Customer').RecordTypeId;
        
        return database.getQueryLocator([SELECT Id, Name FROM Account WHERE isPersonAccount=true AND RecordTypeId=:customerRecordType]);
    } // end of start
    
    
    
    global void execute(Database.BatchableContext BC, list<Account> scope) {
        
        failedUpdates=0;
        
        List<Account> acctInBatch = [SELECT Id,PersonMailingCity,PersonMailingStreet,PersonHomePhone, PersonMobilePhone(SELECT Id,Name,HomePhone__c, Organisation__c,addressLine2__c,addressLine1__c FROM Addresses__r
              where     sourceSystem__c!=NUll  and     sourceSystem__c!='wewe' and sourceSystem__c !='wewe'and sourceSystem__c!='eoei' and
             addressKey__c!=Null and Organisation__c != Null and Organisation__r.RecordTypeId=:customerRecordType and Organisation__r.Id != Null  )
              FROM Account
              WHERE Id IN :scope ];
        
        List <address__c> custMatch= new List <address__c>();
        Map<Id, Account> mapObj2=new Map<Id, Account>();
        
        for (Account acct : acctInBatch) {
            if (acct.Addresses__r.isEmpty()) //check if it empty
                continue;
            for (address__c a : acct.Addresses__r) {
               
                
                if(acct.PersonHomePhone!=a.HomePhone__c){
                    a.Postal_Code_No_Match__c=true;}
                else{a.Postal_Code_No_Match__c=false;}
                if(acct.PersonMailingStreet!=a.addressLine1__c){
                    a.AddressLine1NoMatch__c= true;}
                else{a.AddressLine1NoMatch__c=false;}
                if(acct.PersonMailingCity!=a.ZL_addressLine2__c){
                    a.Address_Line_2_No_Match__c= true;}
                else{a.Address_Line_2_No_Match__c=false;}
                
                
          
                custMatch.add(a);
            }// end of address__c loop
            
        }//end of Account For loop
        
       
        
        system.debug(custMatch.size());
        List<Database.SaveResult> dsrs = Database.update(custMatch, false);
        for(Database.SaveResult dsr : dsrs){
            if(!dsr.isSuccess()){
                failedUpdates++;
            }
            
        }     // end of database update loop
        
        
    } 
    
    global void finish(Database.BatchableContext BC) {
        
        AsyncApexJob a = [SELECT id, ApexClassId, 
                          JobItemsProcessed, 
                          TotalJobItems, 
                          NumberOfErrors, 
                          CreatedBy.Email 
                          FROM AsyncApexJob 
                          WHERE id = :BC.getJobId()];
        
        String emailMessage = 
            'Your batch job '
            + 'AccountCustomerMatchBathJob' 
            + ' has finished.  It executed ' 
            + a.totalJobItems +
            ' batches.  Of which, ' 
            + a.jobitemsprocessed 
            + ' processed without any exceptions' 
            + 'thrown and ' 
            + a.numberOfErrors +
            ' batches threw unhandled exceptions.'
            + '  Of the batches that executed without error' 
            + failedUpdates 
            + ' records were not updated successfully.';
        
        Messaging.SingleEmailMessage mail = 
            new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] 
        {a.createdBy.email, 'blala@yahoo.com'};
            mail.setToAddresses(toAddresses);
        mail.setReplyTo();
        mail.setSenderDisplayName('Batch Job Summary');
        mail.setSubject('Batch job completed');
        mail.setPlainTextBody(emailMessage);
        mail.setHtmlBody(emailMessage);
        Messaging.sendEmail(new 
                            Messaging.SingleEmailMessage[] { mail });
                            
                            
    @istest

public class MatchingAdd {
    
    
    static testMethod void testMatching(){
        MatchingAddBatch obj = new MatchingAddBatch();
        String RecTypeId = GlobalUitlity.getRecordTypeIdByName('Account','Customer');   
        String query = 'SELECT Id, Name FROM Account WHERE isPersonAccount=true ' +
            
            'WHERE Id NOT IN (SELECT Organisation__c FROM address__r)';
        
      
        
        List<Account> lstCustomerAccountOneMatch = new List<Account>();
        List<Contact> conList = new List<Contact>();
        List <address__c> custMatch= new List <address__c>();
        
        
        Account a = new Account(FirstName='Bla' , LastName = 'AccTwoEmailMatch', RecordTypeId = RecTypeId, PersonEmail = 'TwoMatch@mail.com', 
                                goneAway__pc=true ,PersonMailingPostalCode= 'abdewi', 
                                PersonMailingStreet = 'my house,21456', PersonMailingCity='town');
        lstCustomerAccountOneMatch.add(a); 
        system.debug(lstCustomerAccountOneMatch.size()); 
        system.debug(a.Name);
        
        insert lstCustomerAccountOneMatch;
        
        
        Contact con =new Contact( FirstName=a.FirstName, LastName=a.LastName
                                );
        conlist.add(con);   
        insert conList;
        system.debug(conList.size()); 
        system.debug(con.LastName);
        
        
        
        address__c addre = new address__c(  GoneAway__c=true, postalCode__c=a.PersonMailingPostalCode, Organisation__c=a.id, contact__c=con.id,
                                                addressLine1__c =a.PersonMailingStreet, addressLine2__c=a.PersonMailingCity
                                                
                                               );  
        custMatch.add(addre);  
        insert custMatch;           
      
         
         
       Test.startTest();
     //   obj.execute(null,[select id from account]);
      
        
        DataBase.executeBatch(obj, 200); 
        
       Test.stopTest();
    Integer listCont = [select COUNT() from address__c where Organisation__c = :a.id ];
    System.assertEquals(1, listCont); 
        
        
    }// end of test method
    
    
}// end of Class                        
                            
        
        
          
        
    } 
}
Rahul Chaudhary OfficialRahul Chaudhary Official
I suggest that rather having single test method break your class into chunk of logical blocks and setup test data for each block. you can maintain single test object but keep changing data that will be easier..

In other words each if block or function should be testable ... that will give you flexibility