Adding a Wait / Sleep / Pause for Salesforce Unit Testing

There are certain scenarios where there are timing issues that cannot be avoided in Salesforce. For instance: in a trigger handler class, you may have to institute some logic to only execute a block of code if certain conditions are met such as an object hasn’t been modified in the last X seconds, perhaps even due to some 3rd party packages your organization has adopted that requires you to work around timing. Or something has a very short cache life in order to prevent many back-to-back SOQL calls. But then when it comes time to test that class, how do you go the other way and MAKE it wait those X seconds to execute that code and make sure that code has been tested properly? If the wait time is less than 10 seconds, there is a way*.

You can add this construct where you need to wait:

// 8 second "pause" to allow testing of code
Long startTime = DateTime.now().getTime();
Long finalTime = DateTime.now().getTime();
Long millisecondsToWait = 8000; // vary this depending on your "sleep" needs
while (finalTime - startTime < millisecondsToWait) {
finalTime = DateTime.now().getTime();
}

*To be clear, this is for Test classes and code coverage purposes — not something that should be executed in day-to-day business logic normal operation of your user-facing site. This is not a true thread “sleep” and the Salesforce CPU will be cranking while this is taking place, so there are governor limits at play: 10,000 milliseconds for synchronous calls; 60,000 milliseconds for asynchronous calls (reference).

Leave a Reply

Your email address will not be published. Required fields are marked *