function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Lynn the AFTD SysAdminLynn the AFTD SysAdmin 

Messaging.SingleEmailMessage Test Code

I have the following trigger on Contacts to send an email to one of our managers when a contact 'deactivated', however I don't know how to test the Messaging.SingleEmailMessage() code and my test covereage is not enough:

trigger InactiveNotificationTrigger on Contact (after update) {
    
    for (Contact c : Trigger.new){
        
        if(Trigger.oldMap.get(c.id).Record_Status__c == 'Active' && c.Record_Status__c == 'Inactive'){

            List<ID> ModID = New List<ID>();
            ModID.add(c.LastModifiedById);
            string FullEmailTxt;

            List<User> ModUser = [Select ID, name from user where ID in: ModID];
            for(integer i = 0 ; i < ModUser.size(); i++){
                string emailTxt1 = 'Dear Development and Communications Director, ';
                string emailtxt2 = 'The contact, '+c.FirstName+''+c.LastName+', has been marked inactive by '+ModUser[i].name+' on '+c.LastModifiedDate+'.'; 
                string emailTxt3 = 'To review the contact please follow the link: '+System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+c.Id+'.'; 
                FullEmailTxt = emailTxt1+'\n'+'\n'+emailTxt2+'\n'+'\n'+emailTxt3+'\n'+'\n'+'Cheers!';
            }
            
    
            List<User> DevComMng = [Select ID, email from user where Title = 'DevComm Director'];
// for testing only List<User> DevComMng = [Select ID, email from user where Name = 'System Administrator'];
            for(integer i = 0 ; i < DevComMng.size(); i++){
                
                String[] toAddresses = new String[] {DevComMng[i].email};
                    
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setToAddresses(toAddresses);
                email.setSenderDisplayName('Salesforce Administration');
                email.setSubject('Inactive Contact Allert');
                email.setBccSender(false);
                email.setPlainTextBody(FullEmailTxt);
                email.setSaveAsActivity(false);
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
                
            }
            
            Note n = new note();
                n.ParentID = c.id; n.Title = 'Inactive Notification Sent'; n.body = FullEmailTxt;
            insert n;
        }
    }
}

Here the test code I have now:
@isTest
private class TestInactiveNotificationTrigger {

    @isTest static void TestInactiveNotificationTrigger() {
        // Test data setup
        // Create a Board Campaign and assign and insert a current and former board member
        Contact con = new Contact(FirstName='Test',LastName='Contact');
        insert con;
        
        con.Status__c = 'Inactive';
//        con.Inactive_Reason__c = 'Deceased';
        update con;

        // Verify 
        // In this case the inserted contact record should have been updated as GRE Volunteer by the trigger,
        // so verify that we got back an empty search.
        List<ID> nID = New List<ID>();
        nID.add(con.id);
            List<Note> n = [SELECT id FROM Note WHERE ParentID in : nID];
            System.assert( (n.size() == 0), 'Notification Trigger failed.');
        
    }
}
Best Answer chosen by Lynn the AFTD SysAdmin
David ZhuDavid Zhu
You may modify the following code to cover your trigger. You may want to uncomment two lines of system.assertequals.

BTW, you may also need to follow the best practice of trigger coding. Specifically, do NOT put SOQL in for loop. Salesforce trigger is bulking operation.

i.e line: List<User> DevComMng = [Select ID, email from user where Title = 'DevComm Director'];
 
Profile p = [SELECT Id FROM Profile WHERE Name='yourprofile'];
        
        User u1 = new User(Alias = 'testusr1', Email='testuser1@testorg.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='testuser1@dev.com');

        User usrdirector = new User(Alias = 'testusr2', Email='testuser2@testorg.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='testuser2@dev.com',Title='DevComm Director');

	system.runas(u1)
	{
		Integer emailbefore = Limits.getEmailInvocations();

	        Contact con = new Contact(FirstName='Test',LastName='Contact',status__c = 'Active');
	        insert con;
        
        	con.Status__c = 'Inactive';
	        update con;
		
		//system.assertEquals(emailbefore-1,Limits.getEmailInvocations());  //verify one email sent (to usrdirector)
		//system.assertEquals(1,[select id from note].sizeof()); //verify new note record inserted.

	}