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
AkshuAkshu 

test class for batch class to send email to opportunity

/*
 * Write a batch class to send an email to Opportunity owner. 
 * On 1st of each month send an email to Opportunity owner if close date is in this month.
 */
public class Sendmailcopy implements Database.Batchable <sobject> { 
     public Database.QueryLocator start(DataBase.BatchableContext BC){
        return Database.getQueryLocator([select id, Name, OwnerId,Owner.Email,CloseDate from Opportunity where CloseDate=THIS_MONTH]);
    }
      List<String> emailList=new List<String>();
      
    public void execute(Database.BatchableContext BC,List<Opportunity> opptyList){
        
        
        for(Opportunity opp:opptyList)
        {
            emailList.add(opp.Owner.Email);
        }
        sendmail();
    }
    public void sendmail()
    { 
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(emailList);
        email.setSubject(' opportunity Close Date!!!!!');
        email.setPlainTextBody('Close date of this opportunity is in this month');
        
        Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
    }
   public void finish(Database.BatchableContext BC){
    }
}

/*************schedule*************************
 global class sendmail implements Schedulable {
    global void execute(SchedulableContext ctx) {
        Sendmailcopy um=new Sendmailcopy();
        Database.executeBatch(um);
    }
}
*/
Suraj Tripathi 47Suraj Tripathi 47

Hi,
Please find the solution.

@isTest
public class SendmailcopyTest {
    public static testMethod Void startTest(){
        Opportunity testOpportunity = new Opportunity(
            StageName = 'Sourcing Demand',
            CloseDate = Date.today(),
            Name = 'Test Opportunity'
        );
        insert testOpportunity;
        system.debug('testOpportunity::'+testOpportunity);

        Test.startTest();
        Sendmailcopy obj = new Sendmailcopy();
        Database.executeBatch(obj);
        Test.stopTest();
        
    }

}

Please let me know it is working or not.


Please mark it as the Best Answer so that other people would take references from it.

ThankYou

CharuDuttCharuDutt
Hii Akshu
Try Below Code
@isTest
public class BatchTest {
    public static Void uniytTest(){
        Opportunity Opp = new Opportunity();
 Opp.Name = 'Test Opportunity';
 Opp.StageName = 'Closed Won';
 Opp.CloseDate = System.today();
        insert Opp;
       

        Test.startTest();
        Sendmailcopy smc = new Sendmailcopy();
        Database.executeBatch(smc);
        Test.stopTest();
        
    }

}
Please Mark It As The Best Answer If It Helps
ThankYou