-1

How do I test a email messaging trigger? Below is my code and I am trying to test the code for sending email. How do I perform the assertion?

I have the below trigger:

trigger SendEmailToHiringManger on SFDC_Job_Opening__c (after insert, after update) {

    list<SFDC_Job_Opening__c> i = [select SO__c,SFDC_Job_Opening__c.Hiring_Manager__r.email,Account_Name__c from SFDC_Job_Opening__c where id IN:trigger.newMap.keySet()];

    for( SFDC_Job_Opening__c s : i)
    {
        if(s.Hiring_Manager__c != trigger.oldMap.get(s.Id).Hiring_Manager__c){
        system.debug('Name is'+ s.Hiring_Manager__c);
        String userEmail = s.Hiring_Manager__r.email; 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
        String[] toAddresses = new String[] {userEmail}; 
        mail.setToAddresses(toAddresses); 
        mail.setSubject('You have a project assigned' + ' So#- '+ s.SO__c); 
        String body = 'Project Assigned' + '-' + s.SO__c + ' ' + s.Account_Name__c ; 
        mail.setPlainTextBody(body); 
        Messaging.sendEmail(new Messaging.SingleEMailMessage[]{mail});
        }
    }

}

1 Answer 1

3

You can write a test class that updates a "SFDC_Job_Opening__c" record.

Messaging.sendEmail(..) can't be tested using testmethods as testmethods won't send emails.

The code will be 'invoked' but the email will not be sent (for obvious reasons - your testmethods could spam legitimate email addresses).

So you will get some "coverage" to your trigger.

By the way you should check the best coding practices on how to write a better trigger and handlers here

You must log in to answer this question.

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