0

I have a future job that is called from an enqueued job. The code works fine when I run manual tests; however, when my test class, which looks like the code below doesn't finish the future job:

Test.startTest();
system.enqueueJob(new EnqueuableClass([InputParameters]));
Test.stopTest();
System.assertEquals(true, futureJobIsComplete());

When I remove "@future" from the method and rerun the same test method, the assertion works fine. This problem looks very similar to this in nature but they are talking about batch from schedulable and not future from queueable but I would not be surprised if the root cause is the same. Any ideas on what is causing this and how I can resolve it?

UPDATE: All futureJobIsComplete() does is to query the database to assert the records that the futureJob was supposed to update are updated.

| improve this question | | | | |
3

Calling Test.stopTest() only forces any asynchronous processing which is already enqueued to fire. It does not affect any subsequent asynchronous processing kicked off by those jobs.

   |-------------|------------|----------->
startTest    enqueueJob    stopTest
                            job runs synchronously
                            future invoked
                              |------------------->
                             future runs asynchronously
                             since stopTest hasn't been called since invocation

If you have a job which kicks off further asynchronous processing, test the execute method separately from your enqueueJob.

@IsTest
static void testJob()
{
    Test.startTest();
        system.enqueueJob(new MyJob());
    Test.stopTest();

    // assert on what you can
}
@IsTest
static void testJobExecute()
{
    Test.startTest();
        new MyJob().execute(/*context*/ null);
        Integer futureCalls = Limits.getFutureCalls();
    Test.stopTest();

    system.assertEquals(1, futureCalls, 'The future method should be called');
    // assert on future method behavior
}
| 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.