Process Change Event Messages in Apex Triggers

With Apex change event triggers, you can now process change event messages on the Lightning Platform. Change event triggers run asynchronously after the database transaction is completed. Perform resource-intensive business logic asynchronously in the change event trigger and keep transaction-based logic in the Apex object trigger. By decoupling the processing of changes, change event triggers can help reduce transaction processing time.

Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.

How: Each change event processed in the trigger contains the record fields and metadata information about the change in header fields.

A change event trigger is an “after-insert” trigger, defined with the after insert keyword. The trigger fires after the change event message is published. You create an after-insert trigger in the Developer Console the same way you create an Apex object trigger. When you create a trigger, pick the change event object from the sObject dropdown, which is populated with the change events available in your org. For a supported standard object, the change event name is StandardObjectNameChangeEvent. For a custom object, the change event name is CustomObjectName__ChangeEvent.

Example

This trigger shows a simple change event trigger on AccountChangeEvent.

trigger MyAccountChangeTrigger on AccountChangeEvent (after insert) {
   for (AccountChangeEvent event : Trigger.New) {
      // Process event messages
   }
}

Testing Change Event Triggers

Before you can package or deploy Apex change event triggers to production, you must provide Apex tests and sufficient code coverage.

To test change event triggers, enable the generation of change event notifications for the test method.

Test.enableChangeDataCapture();

The Test.enableChangeDataCapture() method ensures that Apex tests can fire change event triggers regardless of the entities selected in Setup. This method doesn’t affect the Change Data Capture entity selections for the org.

After performing DML operations, deliver the event messages to the corresponding trigger with:

Test.getEventBus().deliver();

Alternatively, if you use the Test.startTest(), Test.stopTest() method block in your test, change event messages fire the associated trigger after Test.stopTest() executes.

Example

This test method outlines the order of statements that must be executed in a test, starting with enabling Change Data Capture entities.

@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
    // ...
}