+ Start a Discussion
Margaret Martin 4Margaret Martin 4 

What user executes @future methods?

Hey guys -
I have a unit test that is exhibiting surprising behavior. In our code there is a trigger on Contact that runs when the contact is inserted/updated & in that trigger there is a future method (callout=true if that makes any difference) that also executes on insert/update.

I have a unit test that runs as a Community user. In the test setup, running as a different admin user, a Contact is created and then the test is run as the Community user.

In the log output, the trigger runs as the admin user & invokes the future method, effectively putting it on the 'future queue'. My expectation was that the @future method would execute as the same user that ran the initial trigger, or - possibly - that it would run in system mode. But what I am seeing is that when the @future method is executed, it is executed as the current user. 

Can I really not know what user my future methods will run as? Is this a bug in the testing framework? Can anyone shed some light on this issue?


Eric PepinEric Pepin
Try using Test.startTest() and Test.stopTest() to get control of the completion of future calls so that they can be properly executed and asserted within the testing framework. See solution here for more details: https://salesforce.stackexchange.com/questions/173723/future-runs-in-test-without-test-stoptest-can-that-be