May 13, 2020

Test Class for EmailMessage and EmailMessageRelation in Salesforce

Sample Code:

Apex Class:

public class EmailMessageHandler {
   
    public static void insertEM( String recordId ) {
       
        EmailMessage emailMessage = new EmailMessage(); 
        emailMessage.status = '3'; // email was sent 
        emailMessage.fromName = 'Magulan Duraipandian'; // from name 
        emailMessage.subject = 'This is the Subject!'; // email subject 
        emailMessage.htmlBody = '<html><body><b>Hello</b></body></html>'; // email body 
        //Lead Id 
        String[] toIds = new String[]{ recordId };  
        emailMessage.toIds = toIds; 
        // additional recipients who don’t have a corresponding contact, lead or user id in the Salesforce org (optional) 
        //emailMessage.toAddress = 'emailnotinsalesforce@toexample.com, anotherone@toexample.com'; 
        insert emailMessage; // insert 
         
        // Add Email Message Relation for id of the sender 
        EmailMessageRelation emr = new EmailMessageRelation(); 
        emr.emailMessageId = emailMessage.Id; 
        emr.relationId = recordId; 
        emr.relationType = 'FromAddress'; 
        insert emr;
       
    }

}

Test Class:

@isTest
public class EmailMessageHandlerTest {

    @isTest
    public static void testEM() {
       
        Lead objLead = new Lead( LastName = 'Test', Company = 'Example', Email = 'test1@dgma.com' );
        insert objLead;
        Test.startTest();
        EmailMessageHandler.insertEM( objLead.Id );
        Test.stopTest();
       
    }
   
}

No comments:

Post a Comment