Sub topic 14
Testing change event triggers
This chapter assumes you can write Apex tests with @isTest, DML, and System.assertEquals. It also assumes you have read the chapters on the anatomy of a change event and on Apex triggers for change events. It shows how to run a change event trigger inside a test and how to structure the logic so it is easy to verify.
Why change event triggers need special test handling
In production, a change event is published after the original transaction commits. A trigger on the change event then runs in a separate transaction, as the Automated Process user. Neither step happens inside the DML statement your test issues, so a test that only calls insert and then queries for results sees nothing. The trigger has not run yet.
Two things are needed in the test:
- Turn on change event publishing for the test, because the test does not rely on your Setup configuration.
- Deliver the published events on demand, so the trigger runs before your assertions.
| Need | Apex call | What it does |
|---|---|---|
| Publish change events in a test | `Test.enableChangeDataCapture()` | Makes DML in the test generate change events. |
| Run the change event trigger now | `Test.getEventBus().deliver()` | Delivers pending events and runs the subscribed triggers. |
If you do not call deliver(), pending events are also delivered when Test.stopTest() runs. Calling deliver() explicitly is clearer, and it lets you assert in the middle of a test.
The delivery flow in a test
The diagram shows what happens for one DML statement followed by one deliver() call.
A first test
The trigger under test is the one from the previous chapter. It creates one Task for each record whose Phone field changed in an UPDATE event.
trigger AccountChangeTrigger on AccountChangeEvent (after insert) {
List<Task> followUps = new List<Task>();
for (AccountChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
if (header.changeType == 'UPDATE' && header.changedFields.contains('Phone')) {
for (String recordId : header.recordIds) {
followUps.add(new Task(
Subject = 'Verify updated phone number',
WhatId = recordId
));
}
}
}
if (!followUps.isEmpty()) {
insert followUps;
}
}The test enables change data capture first, then delivers after each DML step:
@isTest
private class AccountChangeTriggerTest {
@isTest
static void createsTaskWhenPhoneChanges() {
Test.enableChangeDataCapture();
Account acct = new Account(Name = 'Acme');
insert acct;
Test.getEventBus().deliver();
acct.Phone = '555-0100';
update acct;
Test.getEventBus().deliver();
System.assertEquals(1, [SELECT COUNT() FROM Task WHERE WhatId = :acct.Id]);
}
}The first deliver() flushes the CREATE event so it cannot be confused with the update. The trigger ignores it, because its changeType is not UPDATE. The second deliver() runs the trigger with the UPDATE event, and the assertion then sees the Task.
Testing the negative cases
A trigger that fires too often is as wrong as one that never fires. Add tests for the cases it must ignore.
@isTest
private class AccountChangeTriggerNegativeTest {
@isTest
static void noTaskWhenOtherFieldChanges() {
Test.enableChangeDataCapture();
Account acct = new Account(Name = 'Acme');
insert acct;
Test.getEventBus().deliver();
acct.Description = 'Updated description';
update acct;
Test.getEventBus().deliver();
System.assertEquals(0, [SELECT COUNT() FROM Task WHERE WhatId = :acct.Id]);
}
@isTest
static void noTaskOnDelete() {
Test.enableChangeDataCapture();
Account acct = new Account(Name = 'Acme', Phone = '555-0100');
insert acct;
Test.getEventBus().deliver();
delete acct;
Test.getEventBus().deliver();
System.assertEquals(0, [SELECT COUNT() FROM Task WHERE WhatId = :acct.Id]);
}
}The delete test queries by WhatId on an ID that no longer exists as an Account. That is fine, because the query only needs the ID value, and it confirms that no Task was created for the deleted record.
Testing bulk behavior
Platform logic runs on batches. When many records change in one transaction, the platform can group them into a single change event whose recordIds list holds several IDs. Your trigger must loop over recordIds, not assume one record per event. A bulk test checks this.
@isTest
private class AccountChangeTriggerBulkTest {
@isTest
static void createsOneTaskPerChangedAccount() {
Test.enableChangeDataCapture();
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Bulk ' + i));
}
insert accounts;
Test.getEventBus().deliver();
for (Account a : accounts) {
a.Phone = '555-0100';
}
update accounts;
Test.getEventBus().deliver();
System.assertEquals(200, [SELECT COUNT() FROM Task WHERE Subject = 'Verify updated phone number']);
}
}Do not assert on how many events the platform produced. The grouping of records into events is an internal detail. Assert on the outcome, which here is one Task per record.
Separating logic from the trigger
You cannot construct an EventBus.ChangeEventHeader yourself, and you cannot publish a change event by hand. That limits how directly you can test a trigger. The usual solution is to keep the trigger thin and move the decision logic into a class that takes plain values.
public with sharing class AccountChangeHandler {
public static List<Task> buildFollowUps(
String changeType,
List<String> changedFields,
List<String> recordIds
) {
List<Task> followUps = new List<Task>();
if (changeType == 'UPDATE' && changedFields.contains('Phone')) {
for (String recordId : recordIds) {
followUps.add(new Task(
Subject = 'Verify updated phone number',
WhatId = recordId
));
}
}
return followUps;
}
}The trigger then only translates the event into arguments:
trigger AccountChangeTrigger on AccountChangeEvent (after insert) {
List<Task> followUps = new List<Task>();
for (AccountChangeEvent event : Trigger.new) {
EventBus.ChangeEventHeader header = event.ChangeEventHeader;
followUps.addAll(AccountChangeHandler.buildFollowUps(
header.changeType, header.changedFields, header.recordIds
));
}
if (!followUps.isEmpty()) {
insert followUps;
}
}Now the rules can be checked with plain unit tests that need no events, with no deliver() calls and no DML:
@isTest
private class AccountChangeHandlerTest {
@isTest
static void buildsTaskForPhoneUpdate() {
List<Task> result = AccountChangeHandler.buildFollowUps(
'UPDATE',
new List<String>{ 'Phone' },
new List<String>{ '001000000000001AAA' }
);
System.assertEquals(1, result.size());
System.assertEquals('001000000000001AAA', result[0].WhatId);
}
@isTest
static void ignoresCreate() {
List<Task> result = AccountChangeHandler.buildFollowUps(
'CREATE',
new List<String>(),
new List<String>{ '001000000000001AAA' }
);
System.assertEquals(0, result.size());
}
}Keep one or two end-to-end tests with deliver() to prove the wiring, and cover the rules with handler tests.
Common problems
- The assertion sees no results. The usual cause is a missing
deliver(), or adeliver()placed before the DML instead of after it. - No events are generated. Check that
Test.enableChangeDataCapture()runs before the DML, in the same test method. - A test fails only in a full-sandbox run. Other automation, such as flows or other triggers, can add changes that fire your trigger. Create all test data inside the test and assert on records you created.
- Assertions on
changedFieldsare brittle. An update usually also changes system fields such asLastModifiedDate, as in the earlier example event. Usecontains, not an exact list comparison. - The trigger works in tests and fails in production. The test runs with your test user's context, while the production trigger runs as the Automated Process user. Make sure the trigger does not depend on the running user's permissions or on
UserInfo.
Summary of the testing pattern
- Call
Test.enableChangeDataCapture()at the start of the test. - Perform DML, then call
Test.getEventBus().deliver()to run the trigger. - Assert on side effects such as inserted Tasks, because the events themselves are not queryable.
- Cover bulk input, ignored change types, and unrelated field changes.
- Move decision logic into a plain class so most tests need no events.
Exercise
A test inserts an Account, updates its Phone, and then asserts that a Task exists. The assertion fails with a count of 0, although the trigger works in a sandbox. Test.enableChangeDataCapture() is the first line of the test. What is the most likely missing step, and where should it go?
Show answer
The test never calls Test.getEventBus().deliver(), so the change event trigger has not run when the query executes. Call it after the update statement, and after the insert if you want the CREATE event flushed separately, before the assertion.
Exercise
Why does the chapter recommend asserting on the number of Tasks created instead of the number of change events delivered in the bulk test?
Show answer
The platform decides how to group changed records into events, and one event can carry many record IDs. That grouping is an internal detail that can change. The number of Tasks follows from the trigger's business rule, so it is a stable thing to assert.
Exercise
You cannot create an EventBus.ChangeEventHeader in a test. How can you still unit test the rule "create a Task only for UPDATE events that changed Phone" without any event delivery?
Show answer
Move the rule into a handler class that accepts plain values (changeType, changedFields, recordIds) and returns the Tasks to insert. The trigger passes header values to it, and unit tests call the handler directly with literal arguments.