How to test if outbound email is send

I have a batch that sends out an email notification to the triggering user when something went wrong. The code that does this is called from the finish() method.

I’m now looking for an elegant way to test this and could not find a simple solution. The only thing I could think of is create an email service and have my code send emails there if Test.isRunningTest = true.

Answer

what do you actually want to test? the execution of the code or that the message gets delivered?

how about you delegate it to a separate method sendNotication() which you can test independently. furthermore you can test it via console as well

batch class

global class MyBatch implements Database.Batchable<sObject> {

    // BATCH CONTRACT ...

    global void finish(Database.BatchableContext bc){

        if (MY_CONDITION)
        {
            sendNotification();
        }
    }

    public void sendNotification(){

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        // CONFIGURE MAIL

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

}

test class

@isTest
private class MyBatchTest {
    static testMethod void sendNotificationTest(){

      Test.startTest();
      Integer emailbefore = Limits.getEmailInvocations();
      MyBatch batch = new MyBatch();
      MyBatch.sendNotication();

      system.assertNotEquals(emailbefore,Limits.getEmailInvocations(),'should have decreased');
      Test.stopTest();
    }
}

Attribution
Source : Link , Question Author : Robert Sösemann , Answer Author : Seb Wagner

Leave a Comment