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
Nilima KumariNilima Kumari 

Not able to Cover the Test class for 100% for batch apex class

Hi all

i am new to the apex development, i have been given the task for writing the test class for Emailalertbatclass, but i am not able to cover the excute method, it is only showing 27%, could anyone please help in the covering 100%
 
global class Emailalertbatchclass implements Database.Batchable<sObject>, Schedulable, Database.Stateful {
    
    //Variable Section
    global FINAL String strQuery;
    global FINAL String leadid;
    global List<String> errorMessages = new List<String>();
    
    global Emailalertbatchclass() { 
        this.strQuery = getBatchQuery();
    }
    
    //Returns the Query String to Batch constructor to fetch right records.
    private String getBatchQuery() {
        String strQuery = 'SELECT Id,Name,Status,Email,owner.email,owner.name,ownerid,No_Enquiry_Email_Sent__c,Manager_Email__c,recordtype.name FROM Lead where No_Enquiry_Email_Sent__c=false AND recordtype.name=\'Lead Registration\' AND Lead_Intent_Type__c=\'High Intent Lead\' AND Status=\'Enquiry\' And ((DaysSinceLastActivityDone__c>=0) OR (DayssinceEnquirystage__c >= 0))';
        return strQuery;
    }
    
    //Batch Start method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(strQuery);
    }
    
    //Batch Execute method calls findCostForWoD method
    global void execute(Database.BatchableContext BC, List<sObject> scopeList) {
        System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size());
        
        List<Lead> ld = (List<Lead>) scopeList;
        List<Lead> updatedld = new List<Lead>();
        if(!ld.isEmpty()) { 
            List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
            for (Lead prod : ld)
            {               
                // Step 1: Create a new Email
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                System.debug( 'prod.owner.Email ' + prod.owner.Email);
                String[] toAddresses = new String[] {prod.owner.Email};
                    // Step 2: Set list of people who should get the email
                    if(prod.Manager_Email__c!=null && prod.Manager_Email__c==''){
                        toAddresses.add(prod.Manager_Email__c);
                    }
                mail.setToAddresses(toAddresses);
                System.debug( 'toAddresses ' + toAddresses);
                
                // Step 3: Set who the email is sent from
                mail.setReplyTo(prod.owner.Email);
                mail.setSenderDisplayName('No Activity on Leads for 24hrs');
                
                // (Optional) Set list of people who should be CC'ed
                List<String> ccTo = new List<String>();
                mail.setCcAddresses(ccTo);
                
                // Step 4. Set email contents - you can use variables!
                mail.setSubject('No Activity on Lead for 24hrs');
                String body = 'Dear ' + prod.owner.name + ', <br><br>';
                body += 'This is to notify you that there is no activity done on the respective <b> Lead Name: ';
                body +=prod.Name+'</b>  please find the link below..<br><br>';
                body += 'link to file: '+URL.getSalesforceBaseUrl().toExternalForm()+'/'+prod.id+'<br><br><br> Thanks,<br>Moengage Team</body></html>';
                mail.setHtmlBody(body);
                System.debug( 'body ' + body);
                
                // Step 5. Add your email to the master list
                mailList.add(mail);
                prod.No_Enquiry_Email_Sent__c = true;
                updatedld.add(prod);
                System.debug( 'prod ' + prod);
                
            }
            if(!mailList.isEmpty()) {
                try{
                    Messaging.sendEmail(mailList);
                    update updatedld;
                    system.debug('mailList '+mailList);
                }
                catch (Exception ex) {
                    errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString());
                }
            }
        }
    }  
    
    //Batch Finish method for after execution of batch work
    global void finish(Database.BatchableContext BC) { 
        
    }
    
    //Method which schedules the ProductDownloadBatch
    global void execute(SchedulableContext sc) {        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
    }
}
My Test Class
 
@isTest
public class EmailalertbatchclassTestclass
{
    static testMethod void testmethod1()
    {
        
        Id rcdTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Lead Registration').getRecordTypeId();
        List<Lead> Leadld = new List<Lead>();
        lead ld = new lead();
        ld.FirstName= 'test';
        ld.LastName='Test2';
        ld.status='Enquiry';
        ld.Company = 'fgfh';
        ld.Email = 'Nilu112@gmail.com';
        ld.Manager_Email__c = 'rakeshkumar1998@gmail.com';
        ld.RecordTypeId = rcdTypeId;//added here
        ld.No_Enquiry_Email_Sent__c = false;  //changed true to false
        
        Insert ld;
        Leadld.add(ld); 
        
        Test.startTest();
        ld.FirstName = 'test1';
        update ld;
        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
        
        Test.stopTest();
    }
    public static testMethod void testschedule() {
        Test.StartTest();
        Emailalertbatchclass sh1 = new Emailalertbatchclass();
        String sch = '0 00 01 * * ?'; 
        ID batchprocessid = Database.executeBatch(sh1);
        String jobId = system.schedule('Emailalertbatchclass', sch, sh1);
        System.assert(jobId != null);
        Test.stopTest(); 
    }
}


 
ShirishaShirisha (Salesforce Developers) 
Hi Nilima,

Can you please try the sample test class code mentioned in the below documentation for email alerts:

https://developer.salesforce.com/forums/?id=906F00000005L2wIAE

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Warm Regards,
Shirisha Pathuri