function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Big EarsBig Ears 

Getting async operations to complete before startTest()

All,

 

I have a trigger that sets up new users to follow specific groups and unfollows when users are deactivated. The code works fine, but the test code doesn't. This is because the trigger calls future methods (which I want), but ironically enough, they're not being called quickly enough when I'm setting up the test data for testing. By the time the test starts, I need existing users to be members of the groups (so I can de-activate them), but my code is de-activating the user BEFORE the async has auto-followed them to the group.

 

I know that stopTest() ensures that all the async jobs have been completed. But does StartTest() not ensure that any async methods called during the initial test data creation has completed before the testing begins?

 

Andy

Best Answer chosen by Admin (Salesforce Developers) 
JPClark3JPClark3

Yes, that is a problem with startTest/stopTest. I've always wanted to use them twice in the same method for this reason, and to get additional Queries and DML statements.

 

What we've done is implement the future method twice

@future
public void PerformProcess()  { PerformProcessNow(); }

public void PerformProcessNow()  { [...The Actual Method...] }

 , then check for isRunningTest in the calling procedure.

if (Test.isRunningTest())
    PerformProcessNow();
else
    PerformProcess();

 

All Answers

JPClark3JPClark3

Yes, that is a problem with startTest/stopTest. I've always wanted to use them twice in the same method for this reason, and to get additional Queries and DML statements.

 

What we've done is implement the future method twice

@future
public void PerformProcess()  { PerformProcessNow(); }

public void PerformProcessNow()  { [...The Actual Method...] }

 , then check for isRunningTest in the calling procedure.

if (Test.isRunningTest())
    PerformProcessNow();
else
    PerformProcess();

 

This was selected as the best answer
Big EarsBig Ears

That is very smart. I'll use that!