0

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.

3

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.