[SalesForce] Platform Event Testing: Unexpected Exception: Error processing messages

I've been doing a lot of work with Platform events and found it a fantastic way to implement some domain driven design patterns, decouple code, and separate execution contexts. Unfortunately I've been running into frequent gotchas, the most recent of which is in testing. Running code that, as a side effect, publishes platform events, or even directly publishes an event within Test.startTest(); and Test.stopTest(); consistently throws the following error:

System.UnexpectedException: Error processing messages
Stack Trace 

Class.System.Test.stopTest: line 19, column 1

A test might look something like this:

...

Example_Event__e exev = new Example_Event__e();
exev.Example_Date_Time__c = Datetime.now();


Test.startTest();

Database.SaveResult sr = EventBus.publish(exev);

System.assertEquals(true, sr.isSuccess());

Test.stopTest();

These tests are being run on a developer sandbox on cs19.

Anyone know a workaround to getting my Trigger/Handler for this event to run in a test context? I've tried recompiling classes, and verified that all my platform event triggers and classes using platform events are on API version 42.0. I've also managed to deploy a Platform Event Trigger/Handler to production using a similar test, so I'm confused as to why I'm running into these errors now.

This error only occurs within Test.startTest(); and Test.stopTest(); however omitting the clauses doesn't run the code.

Best Answer

Platform events in test class are unitested differently.

Instead of EventBus.publish(exev); you have to use Test.getEventBus().deliver();

Test.startTest();
// Create test events
// ...
// Publish test events with EventBus.publish()
// ...
// Deliver test events
Test.getEventBus().deliver();
// Perform validation 
// ...
Test.stopTest();

Make sure you put Test.getEventBus().deliver(); between start and stop test.

https://releasenotes.docs.salesforce.com/en-us/summer18/release-notes/rn_platform_events_apex_enhancements_deliver_events.htm This method is only Available after Summer 18. or API v43

For Version 42 and Below:

Create a blank Trigger for your Platform Event Object, SRC:.Unable to unit test code that publishes platform events

Related Topic