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
nallurisivashankarnallurisivashankar 

Test class for batch apex

Hi,

 

I have created batch class, but i am facing problem during code coverage.

can any one tell me how to write test class?

 

here is my class:

 

global class expireNotify implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        Date d = Date.today();
        String soql = 'SELECT Expiry_Date__c, Name, Email_Address__c FROM Member__c WHERE Expiry_Date__c =: d';
        return Database.getQueryLocator(soql);
    }
   
    global void execute(Database.BatchableContext bc, List<Member__c> recs)
    {
        List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
        for(Member__c m : recs)
        {
            List<String> toAddresses = new List<String>();           
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            toAddresses.add(m.Email_Address__c);
            mail.setToAddresses(toAddresses);
            mail.setSubject('Welcome to Sweet 16 Siebel Batch');
            String messageBody = '<html><body>Hi ' + m.Name + ',<br>Your account Expires today. <br>Kindly contact your administrator.<br><br><b>Regards,</b><br>Magulan D</body></html>';
            mail.setHtmlBody(messageBody); 
            mailList.add(mail);          
        } 
        Messaging.sendEmail(mailList);
    }
   
    global void finish(Database.BatchableContext bc)
    {
    }
}

gautam_singhgautam_singh
What error are you facing ?
hitesh90hitesh90

here is your test class for batch apex, giving 100% coverage

 

@istest
public class TestexpireNotify{
    Private Static testmethod void TestexpireNotify(){
        test.startTest();
        Member__c objMember = new Member__c();
        objMember.Name = 'Test';
        objMember.Expiry_Date__c = Date.today();
        objMember.Email_Address__c = 'test@test.com';
        insert objMember;
        
        database.executebatch(new expireNotify());
        test.stopTest();
    }
}

 

important :
Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

 

Thanks,

Hitesh Patel