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
Renuka SharmaRenuka Sharma 

Not able to cover the Code coverage for Execute method for the batch class

Hi Folks

i am working on  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%

Emailalertbatchclass
 
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);
    }
}

test Class
 
@isTest
public class EmailalertbatchclassTestclass
{
    static testMethod void testmethod1()
    {
        List<Lead> Leadld = new List<Lead>();
        lead ld = new lead();
        ld.FirstName= 'test';
        ld.LastName='Test2';
        ld.status='Enquiry';
        ld.Company = 'fgfh';
        ld.Email = 'manjunath.s@proseraa.com';
        ld.Manager_Email__c = 'chandra.s@proseraa.com';
        ld.No_Enquiry_Email_Sent__c = true;
        Insert ld;
        Leadld.add(ld); 
        
        Datetime Yesterday = Datetime.now().addDays(-1);
        Test.setCreatedDate(ld.Id, Yesterday);
        
        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(); 
    }
}

​​​​​​​
SarvaniSarvani
Hi Renuka,

In line 14 of your batch class where there is SOQL query you are fetching only records where all the below conditions are true like No_Enquiry_Email_Sent__c=false,  recordtype.name='Lead Registration' , Lead_Intent_Type__c='High Intent Lead', DaysSinceLastActivityDone__c,DayssinceEnquirystage__c. But I don't see in your test class you are giving any values for the fields though there is field value for No_Enquiry_Email_Sent__c its set as True. Are there any updates on fields when lead is created ?

I would recommend to give all the field values to correct values so that all conditions will be true so that your lead created in test class will be passed to the batch class.

Hope this helps!

Thanks
Renuka SharmaRenuka Sharma
@Sarvani

DaysSinceLastActivityDone__c  and DayssinceEnquirystage__c are both formula fields, how do i define it in the test class
Renuka SharmaRenuka Sharma
For DaysSinceLastActivityDone__c

User-added image

DayssinceEnquirystage__c 

User-added image