The below code is to validate if an email has been sent from the finish method of a batch job using the Limits.getEmailInvocations(). The afterEmail variable is been set to 0 and no email is been sent from the test.
@isTest
static void sendEmailToScheduledJobUser() {
Test.startTest();
Integer beforeEmail = Limits.getEmailInvocations();
Database.executeBatch(new TestBatch(), 50);
Integer afterEmail = Limits.getEmailInvocations();
System.assert(beforeEmail != afterEmail, 'Email not sent to the schedule job user');
Test.stopTest();
}
The finish method of the batch job sends an email.
global void finish(Database.BatchableContext context)
{
sendEmail(context);
}
When executing the batch job in the developer console, I do receive the email. For testing purposes, I have hardcoded the email address in the batch job.