Testing future methods
By its nature, asynchronous Apex methods does not execute on the same thread and in the same execution context as other Apex methods, so when testing we must force the Salesforce test runner to execute any asynchronous Apex methods synchronously to allow us to assert on the operation of the code.
The way by which we will do this for all our asynchronous code is through the use of the Test.startTest()
and Test.stopTest()
methods. These methods define an execution context with its own set of Governor Limits and resources available to it. Any asynchronous code that is invoked after Test.startTest()
is called will be executed synchronously by the test runner when Test.stopTest()
is called. This allows us to verify that our code operates as expected.
Let's say we have the following future method and Apex class to test, which deactivates a user given their record Id
:
public with sharing class DeactivateUser_Future { @future public static void deactivateUser...