2

How can I test that a trigger listener on my platform event object enqueued an async Apex job? My use case for enqueuing an async job is that the job needs to make a callout to an external service. The callout is not possible within the trigger listener itself.

Below is a simplified concept of what I'm trying to do. There doesn't seem to be a way to test that the job was enqueued or executed at the current time, due to what may be a limitation in Test.stopTest().

trigger AsyncHelloEventTrigger on AsyncHelloEvent__e (after insert) {
    System.enqueueJob(new HelloJob(Trigger.new));
}

I thought about wrapping the call to System.enqueueJob in a service, but my next question would be, "How can I stub the service?"

trigger AsyncHelloEventTrigger on AsyncHelloEvent__e (after insert) {
    ApexJobService.getInstance().enqueueJob(new HelloJob(Trigger.new));
}
2

I use a pattern like the below for simple mocking:

public virtual with sharing class MyService
{
    static MyService instance = new MyService();
    @TestVisible static void setMock(MyService mock) { instance = mock; }

    public static Id enqueueJob(List<MyObject__e> records)
    {
        return instance.doEnqueueJob(records);
    }

    protected virtual Id doEnqueueJob(List<MyObject__e> records)
    {
        return system.enqueueJob(new MyQueueable(records));
    }
}

Then in your test you can mock it out quite easily. You don't really need to test what the service does so much as that it gets called.

class MockService extends MyService
{
    Integer calls = 0;
    protected override Id doEnqueueJob(List<MyObject__e> records)
    {
        calls++;
        return null;
    }
}
@IsTest static void testEnqueueJob()
{
    // set up data
    MyService mock = new MockService();

    Test.startTest();
        MyService.setMock(mock);
        // publish events
    Test.stopTest();

    system.assertEquals(1, mock.calls, 'The service should be called');
}
| improve this answer | |
  • 2
    Very interesting, that your solution doesn't even require the Stub API! Thanks Adrian! – Marty C. Feb 21 '18 at 16:44
1

I wrote up an answer to the linked question that might be helpful - https://salesforce.stackexchange.com/a/297694/54914

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.