[SalesForce] Unable to unit test code that publishes platform events

I keep getting a System.UnexpectedException whenever I run unit tests for code that publishes Platform Events. As soon as I call Test.stopTest(), the test fails with System.UnexpectedException: Error processing messages

I have even tried writing a very simple unit test which also fails:

@isTest
private static void samplePublishApplicationUpdateEvent_justPublishingAnEvent_expectToLearnSomething() {
    Application_Update__e updateEvent = new Application_Update__e();
    updateEvent.Application_Id__c = '12345';

    Test.startTest();
    EventBus.publish(updateEvent);
    Test.stopTest();
}

As soon as we hit Test.stopTest(), I receive the System.UnexpectedException failure.

The API version of the classes is 40. The user I am running the tests as has read/create permissions for my platform event.

Does anyone have any ideas?

Best Answer

Answer: Salesforce bug

Workaround: Create a trigger for your platform events.

I reached out to the Official Platform Events community and created a case with Salesforce. This is a Salesforce bug which they are currently working on patching.

The reason my unit tests were failing is because I did not have a trigger for the platform event that was being published.

After creating a trigger for my platform event, the unit tests pass.

The trigger doesn't have any logic in it since our business case don't require it. Our platform event was only meant for external subscribers.

Update as of 7/31/2017: Salesforce has released a patch to avoid the need for this workaround. I was able to verify the fix in our sandbox org by deleting the dummy trigger and running my original unit tests.

That said, I have restored the "dummy trigger" since it is actually helpful for unit tests to make assertions against the events that are published.

Related Topic