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
chiran jeevichiran jeevi 

i want test class for below batchapex

Global  class batchapexopp implements database.batchable<sobject>,database.stateful {
    public  decimal total=0;
    public integer count=0;
  
    Global database.querylocator start(database.BatchableContext BC){
        
        string str='select id, name, amount from opportunity where amount!=null';
        return database.getQueryLocator(str);
        }
    global void execute(database.BatchableContext BC, list<opportunity> scope){
        for(opportunity a:scope)
        {
            total=total+a.amount;
            count+=1;
           
            
        }
    }
    
    global void finish(database.BatchableContext bc){
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'arun.b504@gmail.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Subject Test Message';
message.plainTextBody = 'Total' +'  '+ total +'  '+ 'Records updated sucessfully';
Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        system.debug('total record updated sucessfully'+count);
    }

}
Manish Jha 1Manish Jha 1
Hi Chiranjeevi,

Please find the code below.It will cover 100% of the source code.Please mark this as the best answer if it helps you.

@isTest             
private class Test_batchapexopp
{
    static testmethod void testbatch() 
    {
        Account acc = new Account(Name='Test Account');
        insert acc;
        
        Task tsk = new Task();
        tsk.whatId = acc.Id; 
        tsk.Subject = 'Testing';
        tsk.Status = 'Completed';
        tsk.Priority = 'Normal';
        tsk.ActivityDate = System.today()+15;
        insert tsk ;
                
        List<Opportunity> opps = new List<Opportunity>();
        for (integer i=0; i<50; i++)
        {
            Opportunity opp = new Opportunity();
            opp.AccountId=acc.Id;
            opp.Name='My Opportunity'+i;
            opp.StageName='Prospecting';
            opp.CloseDate=date.today().adddays(i);
            opp.Amount = 10000;
        
            //opp.LastActivityDate = System.today()+15;
            opps.add(opp);
        }
        insert opps;
        
       Test.startTest();
           batchapexopp obj = new  batchapexopp();
           Database.executeBatch(obj, 200);
       Test.stopTest();

    }
}