1
@isTest
public class TestContactEmailTrigger {
    @isTest
    public static void testTrigger() {
        // Create test data
        List<Contact> contacts = new List<Contact>();
        for (Integer i = 0; i < 5; i++) {
            Contact contact = new Contact(
                LastName = 'TestContact' + i,
                Email = 'test' + i + '@example.com',
                Message_sent__c = true
            );
            contacts.add(contact);
        }
        insert contacts;

        // Perform DML operation to trigger the email sending
        Test.startTest();
        for (Contact contact : contacts) {
            contact.Message_sent__c = true;
        }
        update contacts;
        Test.stopTest();

        // Verify the emails are sent correctly
        List<Messaging.SingleEmailMessage> sentEmails = [SELECT Id, ToAddress, Subject, PlainTextBody FROM Messaging.SingleEmailMessage];
        System.assertEquals(5, sentEmails.size());

        // Check the content of the email
        for (Integer i = 0; i < 5; i++) {
            Messaging.SingleEmailMessage email = sentEmails[i];
            Contact contact = contacts[i];
            System.assertEquals(contact.Email, email.getToAddresses()[0]);
            System.assertEquals('Important Update', email.getSubject());
            System.assertEquals('Hello, \n\nThis is an important update regarding your contact information.', email.getPlainTextBody());
        }
    }
}
0

1 Answer 1

2

The Messaging.SingleEmailMessage is not actually an SObject in Salesforce, it is a class that generates a single message email object.

Sent emails are stored as EmailMessages, you can refer to the doc here: EmailMessage Object Reference

Edit: this object stores sent and received emails

1
  • 1
    Possibly worth also directing the OP to resources discussing how to unit test code that includes email sending, such as this or (using mocking frameworks) this.
    – Phil W
    Aug 3, 2023 at 10:15

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