Newer Version Available
Test Your Platform Event in Apex
Use Test.startTest() and Test.stopTest() to test your platform event in Apex.
Create test event objects, and publish them after the Test.startTest() statement. Then call the Test.stopTest() statement to publish the test events. Include your validations after the Test.stopTest() statement.
1Test.startTest();
2// Create test events & publish them
3Test.stopTest();
4// Perform validation hereThis 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 to be defined in the org.
1@isTest
2public class PlatformEventTest {
3 @isTest static void test1() {
4 Test.startTest();
5
6 // Create a test event and publish it
7 Low_Ink__e inkEvent = new Low_Ink__e(Printer_Model__c='MN-123',
8 Serial_Number__c='10013',
9 Ink_Percentage__c=0.15);
10 EventBus.publish(inkEvent);
11
12 Test.stopTest();
13
14 // Perform validation here
15 // Get a case whose subject contains the serial number of the test event.
16 // This case was created by a trigger.
17 List<Case> cases = [SELECT Id FROM Case WHERE
18 Subject LIKE '%:inkEvent.Serial_Number__c'];
19 // Validate that this case was found
20 System.assertEquals(1, cases.size());
21 }
22
23}