Sub topic 13
Delivering platform events with Test.getEventBus().deliver()
This chapter assumes you can write an @IsTest class, you know what Test.startTest and Test.stopTest do, and you have seen a platform event defined in Setup. You should also know that an Apex trigger can subscribe to a platform event. The earlier chapters showed that async work queued inside the test window runs at stopTest. Platform event subscribers follow a similar rule, with one extra tool.
Why platform events need their own step
A platform event is a message that you publish to the event bus. Subscribers, such as an Apex trigger on the event, receive it in a separate transaction after the publisher commits. That is the same problem as with @future: the work happens somewhere else, later, so a test cannot assert on its result right after the publish call.
In a test, the platform does not hand published events to subscribers immediately. It holds them until one of two things happens:
- The test calls
Test.stopTest(). - The test calls
Test.getEventBus().deliver().
Both deliver the events published so far to the subscribers, and the subscriber trigger runs. The trigger runs after the call returns, so you can assert on its effects on the next line.
The example: an event and its subscriber
The examples use a custom platform event named Order_Event__e with one Text field, Order_Number__c. Create it in Setup under Platform Events before you run the code. The subscriber trigger creates a Task for each event it receives.
trigger OrderEventTrigger on Order_Event__e (after insert) {
List<Task> tasks = new List<Task>();
for (Order_Event__e evt : Trigger.new) {
tasks.add(new Task(Subject = 'Process order ' + evt.Order_Number__c));
}
insert tasks;
}Only after insert is available on platform event triggers, so that is the only context you write and test.
Delivering events with deliver()
Test.getEventBus().deliver() delivers every event that the test has published up to that point. The trigger finishes before the method returns.
@IsTest
private class OrderEventTriggerTest {
@IsTest
static void deliverRunsSubscriberTrigger() {
Order_Event__e evt = new Order_Event__e(Order_Number__c = '1001');
Database.SaveResult result = EventBus.publish(evt);
Assert.isTrue(result.isSuccess(), 'The publish call should succeed');
// Nothing has been delivered yet, so the trigger has not run.
Assert.areEqual(0, [SELECT COUNT() FROM Task WHERE Subject = 'Process order 1001']);
Test.getEventBus().deliver();
Assert.areEqual(1, [SELECT COUNT() FROM Task WHERE Subject = 'Process order 1001']);
}
}This test never calls startTest or stopTest. It does not need to, because deliver() does the delivery itself. The first assertion shows the "before" state: a published event does nothing until it is delivered. That check also proves the later assertion is testing the trigger and not leftover data.
Delivering with startTest and stopTest
If your test already uses the test window, stopTest delivers the published events as part of finishing the window. This is the same synchronous behavior you saw with @future and Queueable jobs.
@IsTest
private class OrderEventWindowTest {
@IsTest
static void stopTestDeliversEvents() {
List<Order_Event__e> events = new List<Order_Event__e>();
for (Integer i = 0; i < 3; i++) {
events.add(new Order_Event__e(Order_Number__c = 'W' + i));
}
Test.startTest();
List<Database.SaveResult> results = EventBus.publish(events);
Test.stopTest();
for (Database.SaveResult sr : results) {
Assert.isTrue(sr.isSuccess());
}
Assert.areEqual(3, [SELECT COUNT() FROM Task WHERE Subject LIKE 'Process order W%']);
}
}Publishing a list in one call is the preferred form. It uses one publish call against the limit on event publish calls and lets you check one SaveResult per event.
Choosing between the two
| Approach | When the trigger runs | Use it when |
|---|---|---|
| `Test.stopTest()` | When the test window closes | The test already has a window, or the code under test also queues other async work |
| `Test.getEventBus().deliver()` | At the moment you call it | You want to assert in the middle of a test, or deliver several times in one method |
A common reason to prefer deliver() is a test that needs to check state in stages. Publish, deliver, assert, then run the next action, deliver again and assert again. A single stopTest can only end the window once, so it cannot give you that.
@IsTest
private class OrderEventStagesTest {
@IsTest
static void deliversInTwoStages() {
EventBus.publish(new Order_Event__e(Order_Number__c = 'S1'));
Test.getEventBus().deliver();
Assert.areEqual(1, [SELECT COUNT() FROM Task WHERE Subject LIKE 'Process order S%']);
EventBus.publish(new Order_Event__e(Order_Number__c = 'S2'));
Test.getEventBus().deliver();
Assert.areEqual(2, [SELECT COUNT() FROM Task WHERE Subject LIKE 'Process order S%']);
}
}What happens in each step
The diagram shows the order of events in the first test above. The key point is that the published event waits in the bus until the test asks for delivery.
What you can and cannot check
Keep these points in mind when you write the assertions:
- You assert on the subscriber's effects, not on the event. Platform events are not stored like normal records, so you cannot query
Order_Event__ewith SOQL to see what was published. Check the Task, the field update, or whatever the trigger produces. - Check the
SaveResult.EventBus.publishreturns a result for each event. AfalsefromisSuccess()means the event was never accepted, for example because a required field was missing. The trigger would then never run, and a later "no Task found" failure would hide the real cause. - Delivery covers events published before the call. An event published after
deliver()waits for the nextdeliver()or forstopTest. - The trigger runs with its own limits. The subscriber runs as a separate transaction, so its DML and SOQL counts do not add to the test method's counts. This matches what happens in production, where the subscriber is a different transaction from the publisher.
Testing the publisher side
Often the code under test is the publisher, such as a service method that publishes an event after a business action. You can test that in two ways. The first is to deliver and check the subscriber's effects, as above. That is an end-to-end test. The second is to check only the publish result. A unit test for a publisher can assert isSuccess() and stop there, which keeps the publisher test independent of any subscriber.
public class OrderPublisher {
public static Boolean publishOrder(String orderNumber) {
Database.SaveResult sr = EventBus.publish(new Order_Event__e(Order_Number__c = orderNumber));
return sr.isSuccess();
}
}
@IsTest
private class OrderPublisherTest {
@IsTest
static void publishOrderReturnsTrue() {
Boolean published = OrderPublisher.publishOrder('P100');
Assert.isTrue(published);
}
}Because the event is never delivered in this test, the subscriber trigger does not run. That is the point of this narrower test. Add a second test with deliver() when you also want to cover the subscriber.
Common mistakes
- Asserting right after
publish. The trigger has not run, so the query finds nothing. Calldeliver()orstopTest()first. - Calling
deliver()beforepublish. Delivery only affects events already published. Check the order of your lines if the trigger seems skipped. - Querying the event object. A query on
Order_Event__eis not how you verify a platform event. Query the records the subscriber changes. - Forgetting that a trigger error is separate. If the subscriber throws an exception, the failure does not roll back or fail the publisher's
SaveResult. Assert on the expected result of the trigger, so a silent failure shows up as a missing record. - Mixing up the two delivery paths in one window. If you call
deliver()inside the window, the events are already delivered whenstopTestruns. Do not expectstopTestto deliver them a second time.
Exercises
Exercise
A test publishes an OrderEvent_e, then immediately runs SELECT COUNT() FROM Task WHERE Subject = 'Process order 2002' and asserts the count is 1. The assertion fails with 0, and the subscriber trigger is correct. What is missing, and where do you put it?
Show answer
The event was published but not delivered, so the subscriber trigger never ran. Add Test.getEventBus().deliver(); after EventBus.publish(...) and before the query. Alternatively, wrap the publish call in Test.startTest() and Test.stopTest(), and run the query after stopTest.
Exercise
Why can you not verify a published platform event by running a SOQL query on the event object, and what do you assert on instead?
Show answer
Platform events are messages on the event bus and are not stored as ordinary records, so a SOQL query on them does not show what was published. Assert on the SaveResult from EventBus.publish to confirm the publish succeeded, and on the effects of the subscriber, such as the Task the trigger inserts, after delivery.
Exercise
Write the lines of a test that publishes one OrderEvente with `OrderNumber__c = 'X1'`, delivers it, asserts one Task exists with the subject 'Process order X1', then publishes a second event 'X2' and asserts two Tasks exist whose subject starts with 'Process order X'.
Show answer
EventBus.publish(new OrderEvente(OrderNumber_c = 'X1')); Test.getEventBus().deliver(); Assert.areEqual(1, [SELECT COUNT() FROM Task WHERE Subject = 'Process order X1']); EventBus.publish(new OrderEvent_e(OrderNumber__c = 'X2')); Test.getEventBus().deliver(); Assert.areEqual(2, [SELECT COUNT() FROM Task WHERE Subject LIKE 'Process order X%']);