Newer Version Available

This content describes an older version of this product. View Latest

Deliver Test Event Messages

Deliver test event messages after the Test.stopTest() statement. Alternatively, deliver test event messages at any time with the Test.getEventBus().deliver() method.

Deliver Test Event Messages After Test.stopTest()

To publish platform event messages in an Apex test, enclose the publish statements within Test.startTest() and Test.stopTest() statements. Call the EventBus.publish() method within the Test.startTest() and Test.stopTest() statements. In test context, the EventBus.publish() method enqueues the publish operation. The Test.stopTest() statement causes the event publishing to be carried out and event messages to be delivered to the test event bus. Include your validations after the Test.stopTest() statement. For example, you can validate that a subscribed Apex trigger or a subscribed flow Pause element has performed the expected actions, like creating a Salesforce record.

1// Create test events
2Test.startTest();
3// Publish test events with EventBus.publish()
4Test.stopTest();
5// Perform validations

Example

This sample test class contains two test methods. The testValidEvent() method checks that the event was successfully published and fires the associated trigger. The testInvalidEvent() method verifies that publishing an event with a missing required field fails, and no trigger is fired. The testValidEvent() method creates one Low_Ink__e event. After Test.stopTest(), it executes a SOQL query to verify that a case record is created, which means that the trigger was fired. The second test method follows a similar process but for an invalid test.

This example requires that the Low_Ink__e event and the associated trigger are defined in the org.

1@isTest
2public class EventTest {
3    @isTest static void testValidEvent() {
4        
5        // Create a test event instance
6        Low_Ink__e inkEvent = new Low_Ink__e(Printer_Model__c='MN-123', 
7                                             Serial_Number__c='10013', 
8                                             Ink_Percentage__c=0.15);
9        
10        Test.startTest();
11        
12        // Publish test event
13        Database.SaveResult sr = EventBus.publish(inkEvent);
14            
15        Test.stopTest();
16                
17        // Perform validations here
18        
19        // Verify SaveResult value
20        System.assertEquals(true, sr.isSuccess());
21        
22        // Verify that a case was created by a trigger.
23        List<Case> cases = [SELECT Id FROM Case];
24        // Validate that this case was found
25        System.assertEquals(1, cases.size());
26    }
27    
28    @isTest static void testInvalidEvent() {
29        
30        // Create a test event instance with invalid data.
31        // We assume for this test that the Serial_Number__c field is required.
32        // Publishing with a missing required field should fail.
33        Low_Ink__e inkEvent = new Low_Ink__e(Printer_Model__c='MN-123',  
34                                             Ink_Percentage__c=0.15);
35        
36        Test.startTest();
37        
38        // Publish test event
39        Database.SaveResult sr = EventBus.publish(inkEvent);
40            
41        Test.stopTest();
42                
43        // Perform validations here
44        
45        // Verify SaveResult value - isSuccess should be false
46        System.assertEquals(false, sr.isSuccess());
47        
48        // Log the error message
49        for(Database.Error err : sr.getErrors()) {
50            System.debug('Error returned: ' +
51                        err.getStatusCode() +
52                        ' - ' +
53                        err.getMessage()+' - '+err.getFields());
54        }
55        
56        // Verify that a case was NOT created by a trigger.
57        List<Case> cases = [SELECT Id FROM Case];
58        // Validate that this case was found
59        System.assertEquals(0, cases.size());
60    }
61}

Deliver Test Event Messages on Demand with Test.getEventBus().deliver()

You can control when test event messages are delivered to subscribers by calling Test.getEventBus().deliver(). Use Test.getEventBus().deliver() to deliver test event messages multiple times and verify that subscribers have processed the test events each step of the way. Delivering event messages multiple times is useful for testing sequential processing of events. For example, you can verify sequential actions of a subscriber in a loop within the same test.

Enclose Test.getEventBus().deliver() within the Test.startTest() and Test.stopTest() statement block.

1Test.startTest();
2// Create test events
3// ...
4// Publish test events with EventBus.publish()
5// ...
6// Deliver test events
7Test.getEventBus().deliver();
8// Perform validations 
9// ...
10Test.stopTest();

Also, you can call Test.getEventBus().deliver() in an Apex test method outside the Test.startTest() and Test.stopTest() statement block. Doing so enables you to test event messages with asynchronous Apex.

1Test.startTest();
2// Do some tests
3Test.stopTest();
4
5// Deliver test events
6Test.getEventBus().deliver();

Deliver Test Event Messages Published from Asynchronous Apex

When testing a batch Apex job that publishes BatchApexErrorEvent on failure, use the Test.startTest() and Test.stopTest() statement block with Test.getEventBus().deliver(). The Test.stopTest() call ensures that the asynchronous Apex job executes after this statement. Next, Test.getEventBus().deliver() delivers the event message that the failed batch job published.

This snippet shows how to execute a batch Apex job and deliver event messages. It executes the batch job after Test.stopTest(). This batch job publishes a BatchApexErrorEvent message when a failure occurs through the implementation of Database.RaisesPlatformEvents. After Test.stopTest() runs, a separate Test.getEventBus().deliver() statement is added so that it can deliver the BatchApexErrorEvent.

1try {
2    Test.startTest();
3    Database.executeBatch(new SampleBatchApex());
4    Test.stopTest();
5    // Batch Apex job executes here
6} catch(Exception e) {
7    // Catch any exceptions thrown in the batch job
8}
9
10// The batch job fires BatchApexErrorEvent if it fails, so deliver the event.
11Test.getEventBus().deliver();

Asynchronous Apex also includes queueable Apex and future methods. If a platform event message is published from within those async Apex jobs, they’re delivered after Test.stopTest(). It’s not necessary to add Test.getEventBus().deliver();. The next example shows how to deliver a platform event message that a queueable Apex job publishes. After Test.stopTest(), the queueable job is executed and the event message is delivered.

1Test.startTest();
2System.enqueueJob(new SampleQueueableApex());
3Test.stopTest();
4// Queueable Apex job executes here.
5// The platform event message published by the job is delivered too.

If further platform events are published by downstream processes, add Test.getEventBus().deliver(); to deliver the event messages for each process. For example, if a platform event trigger, which processes the event from the Apex job, publishes another platform event, add a Test.getEventBus().deliver(); statement to deliver the event message.

Note

Example: Deliver Event Messages Individually

This test class publishes an Order_Event__e event message and delivers it using Test.getEventBus().deliver(). It verifies that the trigger processed the event message and created a task. A duplicate event message (an event with the same Event_ID__c custom field value) is published and delivered. The test verifies that the trigger didn’t create a task for the duplicate event.

Before you can run this test class, define a platform event with the name of Order_Event__e and these fields: Event_ID__c of type Text, Order_Number__c of type Text, Has_Shipped__c of type Checkbox.

1@isTest
2public class MyTestClassDeliver {
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              Event_ID__c='123AB', Order_Number__c='12346', Has_Shipped__c=true);
11        Database.SaveResult sr = EventBus.publish(event);   
12
13        // Verify that the publish was successful
14        System.assertEquals(true, sr.isSuccess());
15        
16        // Deliver the test event before Test.stopTest()
17        Test.getEventBus().deliver();        
18        
19        // Check that the case that the trigger created is present.
20        List<Task> tasks = [SELECT Id FROM Task];
21        // Validate that this task was found.
22        // There is only one test task in test context.
23        Integer taskCount = tasks.size();
24        System.assertEquals(1, taskCount);
25        
26        // Publish a duplicate event
27        Order_Event__e dupEvent = new Order_Event__e(
28              Event_ID__c='123AB', Order_Number__c='12346', Has_Shipped__c=true);
29        Database.SaveResult sr2 = EventBus.publish(dupEvent);
30
31        // Verify that the publish was successful.
32        System.assertEquals(true, sr2.isSuccess());
33
34        Test.getEventBus().deliver();        
35        
36        // Get all tasks in test context
37        List<Task> tasksNew = [SELECT Id FROM Task];
38        // Validate that no task was created and 
39        // the number of tasks should not have changed.
40        System.assertEquals(taskCount, tasksNew.size());
41        
42        Test.stopTest();    
43
44    }
45}

This example trigger processes Order_Event__e event messages that the test class publishes.

Because this trigger performs a SOQL query for each event notification received, the Apex governor limit for SOQL queries can be hit.

Note

1trigger OrderTrigger on Order_Event__e (after insert) {
2    // List to hold all cases to be created.
3    List<Task> tasks = new List<Task>();
4    
5    // Get user Id for case owner
6    User usr = [SELECT Id FROM User WHERE Name='Admin User' LIMIT 1];    
7    
8    // Iterate through each notification.
9    for (Order_Event__e event : Trigger.New) {
10        if (event.Has_Shipped__c == true) {
11            // Create task only if it doesn't exist yet for the same order 
12            String eventID = '%' + event.Event_ID__c;
13            List<Task> tasksFromQuery = 
14                [SELECT Id FROM Task WHERE Subject LIKE :eventID];
15            if (tasksFromQuery.size() == 0) {
16                Task t = new Task();
17                t.Priority = 'Medium';
18                t.Subject = 'Follow up on shipped order ' + event.Order_Number__c + 
19                    ' for event ID ' + event.Event_ID__c;
20                t.OwnerId = usr.Id;
21                tasks.add(t);
22            }
23        }
24    }
25    // Insert all tasks in the list.
26    if (tasks.size() > 0) {
27        insert tasks;
28    }
29
30}