I have a Platform Event with a trigger I am writing tests for. This trigger inserts a record and throws a custom exception if there is a DML error. I want to make assertions about the message in that exception.
If I use EventBus.publish()
and Test.stopTest()
, the exception won't be thrown inside the test, since the trigger executes in a separate transaction. So instead, I have my trigger logic in an Apex class, which I can test directly.
So far so good, but here's the wrinkle: my trigger logic sets the OwnerId
of the record I'm creating based on the CreatedById
in the Platform Event. And Apex doesn't allow you to set CreatedById
on the event record directly -- you have to actually create the record. Which is fine if you're using a regular custom object -- you can query that type of info. But Platform Events aren't queryable.
So now I'm getting a DML error, INVALID_CROSS_REFERENCE_KEY: Owner ID: owner cannot be blank
-- but that isn't the DML error I'm trying to test for.
Is there anything I can do to set the CreatedById
on the event? Or alternatively, is there any way to catch exceptions that come from a Platform Event trigger execution?