0 votes
1 view
by

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
    
Test.startTest();
System.runAs(internalUser) {
    // A record is updated and in trigger FlowFinishStep Queueable is queued
}
Test.stopTest();

----- 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) {
        testMethod(teamMemberIds);
    }
}

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.
}

1 Answer

0 votes
by
 
Best answer

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.

Welcome to Memory Exceeded, where you can ask questions and receive answers from other members of the community.
...