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
Mayuri Deshmukh 3Mayuri Deshmukh 3 

How to write test class for below code of deleting lead

Hi, I have written below batch class how can I write test class for this

code:-
global class DeleteLeads_Batch implements Database.Batchable<sObject> {  
    Id rtid = RecordTypeUtil.getRecordTypeIdByDevName('Lead','Digital_Marketing');
    String query = 'select id, Status, recordtype.name from Lead where recordTypeid = rtid AND (LastModifiedDate > LAST_N_DAYS:180 OR Status like \'%Closed%\'';
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC,List<Lead> leadList){    
        delete leadList;
    }
    global void finish(Database.BatchableContext BC){
        System.debug('Job Finished');
    }
}

Thanks,
Mayuri
PrabhaPrabha

What is the error you are getting?

also, small obervation... are you trying to delete the all the closed leads?

Mayuri Deshmukh 3Mayuri Deshmukh 3
Hi,
Yes I am deleting all the closed leads whose recordtype is Digital-Marketing and I am not getting error code is fine.
I wanted to know how can I write test class for this batch class.
can you please help me in doing that?

Thanks,
Mayuri
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Mayuri,

Can you try the below test class.
 
@istest
public class DeleteLeads_BatchTest {
    public static testMethod void updateContact(){
        List<Lead> leadlist= new List<Lead>();
        Id RecordTypeIdLead = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Digital_Marketing').getRecordTypeId();

        for(Integer i=0;i<100;i++){
            
            Lead l= new Lead();
            l.LastName='sample'+i;
            l.Company='sample company'+i;
            l.Status='Closed - Not Converted';
            l.RecordTypeId=RecordTypeIdLead;
            leadlist.add(l);
        }
        insert leadlist;
        
        List<Lead> afterinserted=[select id,Name from lead ];
        system.assertEquals(100, afterinserted.size());
        test.startTest();
        DeleteLeads_Batch bs= new DeleteLeads_Batch();
        database.executeBatch(bs);
        test.stopTest();
    }
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,