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.
The first statement you include in the test method is:
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 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:
- In the Developer Console, select File | New | Apex Class.
- In the Name field, enter a name for the trigger:
TestEmployeeChangeTrigger
. - Replace the default content with the following code.
- In the test class window, click Run Test. After the test finishes execution, the Tests tab shows the status of the test run.
- 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!