Newer Version Available

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

Test Apex Publish Callbacks

To test your Apex publish callback class, add an Apex test class. You must provide Apex tests before you can package or deploy an Apex class to production and meet code coverage requirements.

In an Apex test, event messages are published synchronously in the test event bus. To simulate the execution of the callback methods in a test, you can deliver or fail the publishing of the event messages.

To simulate a failed publishing of an event or a batch of events, call this method.

The Test.getEventBus().fail() method causes the publishing of events to fail immediately after the call, and event messages are removed from the test event bus. This method causes the onFailure() method in the callback class to be invoked. When the event messages fail to publish, none of the triggers defined on the platform event receive any failed events.

To simulate successful event delivery, call the Test.getEventBus().deliver(); method or have your events delivered after Test.stopTest(). Event messages are delivered immediately after each of those statements. Successful event delivery triggers the execution of the onSuccess() method in the callback class.

Example: MyCallbackTest Test Class

This example class is a test class for the FailureAndSuccessCallback class given previously. This test class shows how to test the successful and failed publishing of test event messages in the test event bus. Before you run this test class, define a platform event in Setup with the label Order Event and a Text(18) field of Order Number.

Example: MyCallbackTestWithCorrelation Test Class

This example class is a test class for the FailureCallbackWithCorrelation class given previously. This test class shows how to test the failed publishing of test event messages in the test event bus. The callback retries publishing events for a maximum of two attempts so the test fails the publishing of a test event twice in a loop. It verifies that, each time, the callback retries publishing the event by checking that the retryCounter variable has been increased. Before you run this test class, define a platform event in Setup with the label Order Event and a Text(18) field of Order Number.