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
SFDC Coder 8SFDC Coder 8 

Test class for Batch Apex that deletes records

Hi All,
I am new to Salesforce.
I have written a batch apex to delete records and send a csv file to some email id.
I want to write test class for the same. Here is my code
global class Del_leads implements Database.Batchable<sobject>
{  
       
   Public String s;
   public integer j; 
   Public string k='\n'+'IDName'+','+'CreatedDate';  
   
   
   global Database.QueryLocator start(Database.BatchableContext BC){
      
      return Database.getQueryLocator([SELECT Id,Subject FROM lead]);     
   }
   
global void execute(Database.BatchableContext BC,List<Task> Lds){     
  
    s +=k+'\n'+ lds[j].Id+','+lds[j].CreatedDate;
          
  Blob b=Blob.valueOf(s);
  Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
  efa.setFileName(m+'attachment.csv');
  efa.setBody(b);
        
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
  mail.setToAddresses(new String[] {abc@test.com'});        
  mail.setSenderDisplayName('Batch Processing');
  mail.setSubject('Batch Process Completed');
  mail.setPlainTextBody('Please find the attachment of deleted records');
  mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});     
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });       
  delete Lds;           

}  
   
global void finish(Database.BatchableContext BC){     
  System.debug(LoggingLevel.WARN,'Deleting Leads Finished');
}

}

Please help me
Thanks in Advance
Amit Chaudhary 8Amit Chaudhary 8
@isTest 
public class Del_leadsTest 
{
    static testMethod void testMethod1() 
	{
	
		Lead newLead = new Lead(firstName = 'Cole', lastName = 'Swain', company = 'BlueWave', status = 'contacted' ) ;
		insert 	newLead;
		
		Test.startTest();

			Del_leads obj = new Del_leads();
			obj.j=0;
			DataBase.executeBatch(obj);

		Test.stopTest();
		
	}
}

Let us know if this will help you