Skip to main content

Test the Change Event Trigger

Learning Objectives

After completing this unit, you’ll be able to:

  • Write an Apex test class for the Apex change event trigger.
  • Run the test and provide test coverage for the Apex change event trigger.

Testing the Change Event Trigger

Now that you've learned how to write a change event trigger, let’s write a test for it. Testing your trigger is important not just as a good practice but it is also enforced by the platform. Before you can package or deploy Apex triggers to production, you must provide Apex tests and sufficient code coverage. 

You provide test coverage for the Apex trigger by writing an Apex test class, which includes one or more test methods. The structure of a test method for change event triggers looks as follows.

@isTest static void testChangeEventTrigger() {
    // Enable all Change Data Capture entities for notifications.
    Test.enableChangeDataCapture();
    // Insert one or more test records
    // ...
    // Deliver test change events
    Test.getEventBus().deliver();
    // Verify the change event trigger’s execution
    // ...
}

The first statement you include in the test method is:

Test.enableChangeDataCapture();

This statement enables all entities for Change Data Capture and ensures that Salesforce record changes done in a test method fire change event triggers. This method enables all entities only for the test and doesn’t affect the Change Data Capture entity selections for the org.

After enabling Change Data Capture, perform some DML operations and then call the Test.getEventBus().deliver() method. The method delivers the event messages from the test event bus to the corresponding change event trigger and causes the trigger to fire.

Test.getEventBus().deliver();

Test change events messages are published to the test event bus, which is separate from the Salesforce event bus. They aren’t persisted in Salesforce and aren’t delivered to event channels outside the test class. Properties of test change event messages, like the replay ID, are reset in test context and reflect only the values of test event messages.

Create and Run a Test for the Trigger

Let's get hands-on and create a test class, TestEmployeeChangeTrigger. The test method in the class creates an Employee test record and updates the record. Each of these operations fires the trigger on the Employee change event. The test ensures the trigger execution by querying the task that the trigger created and by verifying the count of tasks.

When running the test class in the Developer Console, the debug logs are available in the Logs tab. For Apex tests, there is no need to set up debug logs in Setup for the Automated Process entity.

To create the test class:

  1. In the Developer Console, select File | New | Apex Class.
  2. In the Name field, enter a name for the trigger: TestEmployeeChangeTrigger.
  3. Replace the default content with the following code.
  4. @isTest
    public class TestEmployeeChangeTrigger {
        @isTest static void testCreateAndUpdateEmployee() {
            // Enable all Change Data Capture entities for notifications.
            Test.enableChangeDataCapture();
            // Insert an Employee test record
            insert new Employee__c(Name='e-101',
                First_Name__c='Astro',
                Last_Name__c='Test',
                Tenure__c=1);
            // Call deliver to fire the trigger and deliver the test change event.
            Test.getEventBus().deliver();
            // VERIFICATIONS
            // Check that the change event trigger created a task.
            Task[] taskList = [SELECT Id,Subject FROM Task];
            System.assertEquals(1, taskList.size(),
                'The change event trigger did not create the expected task.');
            // Update employee record
            Employee__c[] empRecords = [SELECT Id,OwnerId,First_Name__c,Tenure__c FROM Employee__c];
            // There is only one test record, so get the first one
            Employee__c emp = empRecords[0];
            // Debug
            System.debug('Retrieved employee record: ' + emp);
            // Update one field and empty another
            emp.First_Name__c = 'Codey';
            emp.Tenure__c = null;
            update emp;
            // Call deliver to fire the trigger for the update operation.
            Test.getEventBus().deliver();
            // VERIFICATIONS
           // Check that the change event trigger created a task.
           // We should have two tasks now, including one from the first trigger invocation.
          Task[] taskList2 = [SELECT Id,Subject FROM Task];
          System.assertEquals(2, taskList2.size(),
              'The change event trigger did not create the expected task.');
        }
    }
  5. In the test class window, click Run Test. After the test finishes execution, the Tests tab shows the status of the test run.
  6. Click the Tests tab and expand the Overall Code Coverage pane. The code coverage for EmployeeChangeTrigger is at 100%, which is the result of running this test.

You're now all set for writing a change event trigger with a test class so you can deploy it to production!

Resources

Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities