Newer Version Available

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

Test Your Platform Event Trigger in Apex

Ensure that your platform event trigger is working properly by adding an Apex test. Before you can package or deploy any Apex code (including triggers) to production, your Apex code must have tests. To publish platform events in an Apex test, enclose the publish statements within Test.startTest() and Test.stopTest() statements.

Call the publish method within the Test.startTest() and Test.stopTest() statements. In test context, the publish method enqueues the publish operation. The Test.stopTest() statement causes the event publishing to be carried out. Include your validations after the Test.stopTest() statement.

1// Create test events
2Test.startTest();
3// Publish test events 
4Test.stopTest();
5// Perform validation here

This sample test class creates one Low_Ink__e event in a test method. After Test.stopTest(), a SOQL query verifies that the associated trigger was fired. The trigger creates a case. The case subject contains the printer serial number. This example requires the Low_Ink__e event and the associated trigger to be defined in the org.

1@isTest
2public class EventTest {
3    @isTest static void test1() {
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        EventBus.publish(inkEvent);
14        
15        Test.stopTest();
16        
17        // Perform validation here
18        // Get a case whose subject contains the serial number of the test event.
19        // This case was created by a trigger.
20        List<Case> cases = [SELECT Id FROM Case WHERE 
21                        Subject LIKE '%:inkEvent.Serial_Number__c'];
22        // Validate that this case was found
23        System.assertEquals(1, cases.size());
24    }
25
26}