Event and Event Bus Properties in Test Context
Deliver Test Event Messages
Test Retried Event Messages
Encrypting Platform Event Messages at Rest in the Event Bus
Previous Versions
An Apex trigger can retry processing of an event message by throwing EventBus.RetryableException. In API version 43.0 and later, you can test retried event messages by calling Test.EventBus.deliver() and inspecting EventBusSubscriber fields.
To force redelivery of a retried event message in an Apex test, call Test.EventBus.deliver(). This method also delivers other event messages that have been published after the last deliver() call.
In API version 43.0 or later, you can check these new EventBusSubscriber fields to test retried triggers.
RetriesLastErrorThe EventBusSubscriber.Retries field indicates how many times a trigger was retried.
EventBusSubscriber.LastError indicates the error message that was passed to the throw statement that executed last (throw new EventBus.RetryableException('Error Message')).
When EventBus.RetryableException is thrown, EventBusSubscriber.Position isn’t incremented because the trigger didn’t successfully process the event message.
Note
This test method delivers a test event message that fires a trigger. The associated event trigger throws EventBus.RetryableException twice. The test verifies that the trigger was retried twice by querying EventBusSubscriber and checking the Retries field value.
Before you can run this test class, define a platform event with the name of Order_Event__e and the following fields: Order_Number__c of type Text and Has_Shipped__c of type Checkbox. This test class assumes there is an associated trigger called OrderTriggerRetry that retries the event. The trigger is not provided in this example.
1@isTest
2public class MyTestClassRetryDoc {
3
4 @isTest static void doSomeTesting() {
5
6 Test.startTest();
7
8 // Publish a test event
9 Order_Event__e event = new Order_Event__e(
10 Order_Number__c='12345', Has_Shipped__c=true);
11 Database.SaveResult sr = EventBus.publish(event);
12 // Deliver the initial event message.
13 // This will fire the associated event trigger.
14 Test.getEventBus().deliver();
15
16 // Trigger retries event twice, so loop twice
17 for(Integer i=0;i<2;i++) {
18 // Get info about all subscribers to the event
19 EventBusSubscriber[] subscribers =
20 [SELECT Name, Type, Position, Retries, LastError
21 FROM EventBusSubscriber WHERE Topic='Order_Event__e'];
22
23 for (EventBusSubscriber sub : subscribers) {
24 System.debug('sub.Retries=' + sub.Retries);
25 System.debug('sub.lastError=' + sub.lastError);
26 if (sub.Name == 'OrderTriggerRetry') {
27 System.assertEquals(i+1, sub.Retries);
28 }
29 }
30
31 // Deliver the retried event
32 Test.getEventBus().deliver();
33 }
34
35 Test.stopTest();
36
37 }
38}See Also