I am unable to use Queueable Apex in a Platform Event trigger but do not know why. I didn't found any documented limitations on this, so I am wondering if it is indeed possible.
This is my Queueable Apex class:
public class Test_QueueableClass implements Queueable
{
public void execute(QueueableContext context)
{
System.debug('Hello World');
}
}
This is my Platform Event Trigger:
trigger MessageEventTrigger on MessageEvent__e (after insert)
{
System.debug('Trigger Context');
Id jobId = System.enqueueJob(new Test_QueueableClass());
}
Unit Test:
@isTest
private class testTrigger
{
static testMethod void runTest()
{
test.startTest();
Database.SaveResult results = EventBus.publish(new MessageEvent__e(Type__c ='TEST', Body__c='TEST'));
test.stopTest();
}
}
All I see in the debug Log is the 'Trigger Context' message, but not the 'Hello World' message..
Any ideas?
Best Answer
After struggling with this for longer than I'd like to admit, I found a method that enables us to test Platform Event Triggers that enqueue
Queueable
jobs. The magical method is:What you need to do is call
Test.getEventBus().deliver()
after you have calledEventBus.publish(platformEvents)
. Just make sure you do this betweenTest.startTest()
andTest.stopTest()
The gotcha is that YOU MUST call
Test.getEventBus().deliver()
beforeTest.stopTest()
Here's some code to illustrate: