Queueable class from Test context runs in test runner mode and not in System.runAs user. This is strange behaviour. Here is the snippet. Any idea?

User internalUser = // Created Internal User with name as 'JonCT' with System admin, does **NOT** have field 'Test_Status__c' permission
PermissionSetService.assignPermissionSet(internalUser, 'Modified_PS'); does have field 'Test_Status__c' permission
System.runAs(internalUser) {
    // A record is updated and in trigger FlowFinishStep Queueable is queued

----- Main Class Code ----

public class FlowFinishStep implements Queueable {
    public Set<Id> teamMemberIds;

    public FlowFinishStep(Set<Id> teamMemberIds) {
        System.debug('UserInfo check in Constructor -> '+[SELECT Id, FirstName, LastName, Profile.Name FROM User WHERE Id = :UserInfo.getUserId()]);
        this.teamMemberIds = teamMemberIds;
    public void execute(QueueableContext context) {

private static void testMethod(Set<Id> teamMemberIds) {
    System.debug('UserInfo -> '+[SELECT Id, FirstName, LastName, Profile.Name FROM User WHERE Id = :UserInfo.getUserId()]);
    // Here the userinfo changes to System admin who is running the test from UI and not JonCT
    // And the code fails because this system admin does not have `Test_Status__c` permission.

I found, all the way back in 2018, that batches do not execute in the context of the System.runAs user during test executions (read more here, and feel free to upvote that idea to fix this broken behaviour).

I believe you are simply seeing the same for a different async process. Recall that async processes are actually executed during the Test.stopTest method execution and are guaranteed to have completed by the time processing returns from Test.stopTest.

My belief is that Salesforce simply fails to consider the contextual user at the time the async is requested and instead simply applies the contextual user at the time of execution in Test.stopTest.

Try moving the (start and) stop Test method call into the runAs block.

  • 2
    I tried that just after posting this question and yes it works, Thanks. Apr 13 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.