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.

    static void sendEmailToScheduledJobUser() {
        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');

The finish method of the batch job sends an email.

global void finish(Database.BatchableContext 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.

1 Answer 1


The asynchronous code will not run until your test hits Test.stopTest(), at which point the limits reset. You cannot test that asynchronous code sends an email. However, if your sendEmail method will work with a null input, you can call the finish method directly.

    new MyBatch().finish(null);
    Integer emailInvocations = Limits.getEmailInvocations();
  • 1
    Or a static @TestVisible variable to verify the code was called, but most people don't like to use that technique.
    – sfdcfox
    Commented Feb 17, 2019 at 6:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .