Skip to main content
Became Hot Network Question
edited tags
Link
Sebastian Kessel
  • 13.2k
  • 12
  • 38
  • 61
Source Link
number41
  • 980
  • 2
  • 12
  • 31

Testing a Future Method that Schedules a Class - Test.stopTest() Does NOT Run Both Synchronously

I have a class with an @future callout method, and that future method schedules an instance of another class which also makes a callout. In effect, if the first callout is successful, it schedules another callout later on. It is all triggered by a simple field update on the Self_Serve_Trial_Request__c object.

In writing the tests, I was pleasantly surprised to see that the field update ran not only the initial future call out, but also the subsequent scheduled callout. I could see this clearly in the debug log, and I assumed it ran them both synchronously. Great.

However, I then realized that any code after Test.stopTest() did NOT see the changes created by both callouts, but instead only saw changes created by the first. Essentially, Test.stopTest() did NOT make both callouts synchronously, it only made the first one synchronously. So I can only access the context after the first callout, and there is no way for me to access the context after the second callout.

How then can one write a complete end-to-end test, and access the context that exists after both callouts?

 Test.startTest();
       
     Test.setMock(HttpCalloutMock.class, new SelfServeTrialMocks.CreateMachineMock());
        
     Self_Serve_Trial_Request__c SSTR = [Select ID FROM Self_Serve_Trial_Request__c LIMIT 1];                                           
            SSTR.Decision__c = 'Approved';
     update SSTR;
        
 Test.stopTest();
        
 //>>>>> the initial future method runs here, so I can query the record to see those changes... 

     Self_Serve_Trial_Request__c SSTR = [SELECT Environment_ID__c
                                         FROM Self_Serve_Trial_Request__c WHERE ID = :SSTRs.ID];
     system.assert(whatever = whatever);
        
 //>>>>>>BUT NOW my scheduled class runs here, after any other code that I write. I can see it working clearly in the debug logs, but cannot access it. Is there no way to do so?