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
Mayank Upadhyaya 5Mayank Upadhyaya 5 

how to write test class of batch apex

hi  i am new in test classes , could yu please help me to write test class of below batch apex

global class CompositeOppbatchCls implements 
Database.Batchable<sObject>, Database.Stateful {
    
    string ParentOpp;

    global Database.QueryLocator start(Database.BatchableContext bc) {
       ParentOpp = 'SELECT Id, CloseDate, Status__c,Type,Sub_Type__c, Branded_As__c, is_composite__c, Lease_Term_Months__c, Proposed_DAR__c,SS_Pct_2__c,Monitoring_Fee_Air__c,Test_Fee_Air__c, Admin_Fee_Air__c,Free_Air__c,Commission_Equation_Type__c,Straight_Percent__c,Flat_Fee_Amt_Entered_Monthly__c,SS_Pct_1__c,SS_Amount_1_PM__c,Period_Payment__c,Contractual_Vend_Price_Increase__c,Forecast__c,Auto_Renewal__c,Approved_Air_Monthly_Gross_Per_Child__c,Approved_Monthly_Water_Child__c,Approved_Monthly_Air_Child__c,Coin_to_Card_Conversion__c,Approved_Monthly_Vac_Child__c,Initial_Payee__c,Opportunity_Install_Note__c,composite_opportunity__c,ChildOpportunityStage__c,Capital_Date__c ' +
                'FROM Opportunity '+ 'WHERE  Record_Type_Name__c = \'Air Composite Opportunity\' AND Status__c = \'Approved\' AND     Composite_Opp_Check__c = false AND LastModifiedDate = TODAY' ;
            System.debug('Parent Opp ' + ParentOpp);       
        return Database.getQueryLocator(ParentOpp);
        
           
    }

    global void execute(Database.BatchableContext bc, List<Opportunity> Scope){
        // process each batch of records   
    for(Opportunity r : scope){
        
        if ( r.is_composite__c){
            
            r.Composite_Opp_Check__c = true ;
        }
        
       List<Opportunity> ChildOpps = [SELECT Id, CloseDate,
                   Status__c,
                    Type,
                   Sub_Type__c,
                   Branded_As__c,
                   Lease_Term_Months__c,
                   Proposed_DAR__c,
                   Monitoring_Fee_Air__c,
                   Test_Fee_Air__c,
                   Admin_Fee_Air__c,
                   Free_Air__c,
                   Commission_Equation_Type__c,
                   Straight_Percent__c,
                   Flat_Fee_Amt_Entered_Monthly__c,
                   SS_Pct_1__c,
                   SS_Pct_2__c,                  
                   SS_Amount_1_PM__c,
                   Contractual_Vend_Price_Increase__c,                  
                   Period_Payment__c,
                   Forecast__c,
                   Auto_Renewal__c,
                   Coin_to_Card_Conversion__c,
                   Initial_Payee__c,
                   Opportunity_Install_Note__c,
                   composite_opportunity__c,
                   StageName,  
                   Approved_Monthly_Vac_Per_Child__c,
                   Approved_Monthly_Air_Per_Child__c,
                   Approved_Monthly_Water_Per_Child__c,
                   Approved_Monthly_Gross_PM_Per_Child__c,                   
                   Capital_Date__c FROM Opportunity WHERE composite_opportunity__c =:r.Id] ;
        
        System.debug('Child Opps ' + ChildOpps);
        
      for(Opportunity o : ChildOpps){ 
          
         o.CloseDate = r.CloseDate;         
         o.Initial_Payee__c = r.Initial_Payee__c;
         o.Opportunity_Install_Note__c = r.Opportunity_Install_Note__c;
         o.Auto_Renewal__c = r.Auto_Renewal__c;
         o.SS_Amount_1_PM__c = r.SS_Amount_1_PM__c;
         o.Period_Payment__c = r.Period_Payment__c;
         o.Contractual_Vend_Price_Increase__c = r.Contractual_Vend_Price_Increase__c;
         o.Forecast__c = r.Forecast__c;
         o.Coin_to_Card_Conversion__c = r.Coin_to_Card_Conversion__c;
         o.Free_Air__c = r.Free_Air__c;
         o.Admin_Fee_Air__c = r.Admin_Fee_Air__c;
         o.Test_Fee_Air__c = r.Test_Fee_Air__c;
         o.Commission_Equation_Type__c = r.Commission_Equation_Type__c;
         o.Monitoring_Fee_Air__c = r.Monitoring_Fee_Air__c;
         o.Proposed_DAR__c = r.Proposed_DAR__c;
         o.Type = r.Type;
         o.Sub_Type__c = r.Sub_Type__c;
         o.SS_Pct_1__c = r.SS_Pct_1__c;
         o.SS_Pct_2__c = r.SS_Pct_2__c;
         o.Status__c = r.Status__c;
         o.Branded_As__c = r.Branded_As__c;
         o.Straight_Percent__c = r.Straight_Percent__c;
         o.Flat_Fee_Amt_Entered_Monthly__c = r.Flat_Fee_Amt_Entered_Monthly__c;
         o.Capital_Date__c = r.Capital_Date__c;
         o.StageName = r.ChildOpportunityStage__c;
         o.Lease_Term_Months__c = r.Lease_Term_Months__c;
         o.Approved_Monthly_Vac_Per_Child__c = r.Approved_Monthly_Vac_Child__c; 
         o.Approved_Monthly_Air_Per_Child__c = r.Approved_Monthly_Air_Child__c;    
         o.Approved_Monthly_Water_Per_Child__c =  r.Approved_Monthly_Water_Child__c;
         o.Approved_Monthly_Gross_PM_Per_Child__c = r.Approved_Air_Monthly_Gross_Per_Child__c;  
          
        }  
             Update ChildOpps;
           System.debug('Child Opps ' + ChildOpps);
     }
     Update scope;        
    }    

    global void finish(Database.BatchableContext bc){
        //  System.debug(recordsProcessed + ' records processed.');
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, 
                            JobItemsProcessed,
                            TotalJobItems, CreatedBy.Email
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];
          
    }    
}
Mayank Upadhyaya 5Mayank Upadhyaya 5
Hi Charu ,
this batch , i am calling in schedulable batch class . the above mentioned test class would work?
and in my batch class i am updating child opportunities from parent opportunities

Thanks,
Mayank 
CharuDuttCharuDutt
Hii Mayank 
As you said In Your Batch You're Update Child opportunities From Parent Opportunities
In Below Test Class i'm Inserting  One Parent Opportunity ANd one Child Opportunity Rest You Have To Fill The Required Fields

you Have to Change The name of ScheduleClass In Below code 
@isTest
 public Class CompositeOppbatchClsTest{
public static String CRON_EXP = '0 0 0 2 6 ? 2022';
@isTest
public Static Void UnitTest(){
Id RecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Air Composite Opportunity').getRecordTypeId();
 
Account Acc =New Account ();
Acc.name = 'Test Acc';
insert Acc;
Opportunity Opp = new Oppotunity();
opp.Name ='test opp';
opp.AccountId = Acc.id;
opp.Composite_Opp_Check__c  = false;
opp.RecordTypeId  = RecordTypeId ;
/*Fill All Required Fields*/
Insert Opp;
Opp.Status__c = 'Approved';
update opp;

Opportunity Opp2 = new Oppotunity();
opp.composite_opportunity__c = opp.Id;
/*Fill All Required Fields*/
Insert Opp2;

        test.startTest();
     String jobId = System.schedule('test', CRON_EXP, new ScheduleClassName());
        Test.stopTest();
            
}
}
Please Mark It As Best Answer If It Helps
Thank You!
Mayank Upadhyaya 5Mayank Upadhyaya 5
thanks charu , it worked.
Suraj Tripathi 47Suraj Tripathi 47

Hi,

Please find the solution.

@isTest
 public Class CompositeOppbatchClsTest{
public static String CRON_EXP = '0 0 0 2 6 ? 2022';

 Static testmethod Void UnitTest(){
Id oppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Air Composite Opportunity').getRecordTypeId();
 
Account ac =New Account ();
ac.Name = 'Test Data';
insert ac;
Opportunity oppInstance = new Oppotunity();
oppInstance.Name ='opp Data';
oppInstance.AccountId = ac.id;
oppInstance.RecordTypeId  = oppRecordTypeId ;
//oppInstance=> Fill aur required field
 Insert Opp;
oppInstance.Status__c = 'Approved';
update opp;

Opportunity oppInstance2 = new Oppotunity();
oppInstance2.composite_opportunity__c = opp.Id;
//Similarly fill this oppInstance2
 Insert Opp2;

        test.startTest();
     String jobId = System.schedule('test', CRON_EXP, new ScheduleClassName());
        Test.stopTest();
            
}
}
Thank you
Mayank Upadhyaya 5Mayank Upadhyaya 5
Hi Charu,

I have one doubt here. i am using this chrone expression in my scheduler class - '0 0 0,4,8,12,16,20 ? * *'  
should i use the same one is test class also?

Thanks,
Mayank 
CharuDuttCharuDutt
@ Mayank 
No It's Not Necessary As Chrone Expression In test Class Is For Just Testing Purposes

 Please Close Your Query By Marking It As best Answer So It Also Helps Others In Future
Thank You!