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
Mak OneMak One 

How to make static initialization consider user in runAs in Test class


public with sharing class Utils_SDF_Methodology {
.
.
.
    public static final String BypassVar;//List of triggers that can be bypassed
    
    static{
        System.Debug('## >>> Utils_SDF_Methodology constructor :BEGIN <<< run by ' + UserInfo.getName());
        User user=[SELECT UserRole.Name,Profile.Name,BypassTriggers__c FROM User WHERE Id =:UserInfo.getUserId() LIMIT 1];
        BypassVar=';'+user.BypassTriggers__c+';';
        System.Debug('## >>> Utils_SDF_Methodology constructor : END <<<');
    }
.
.
.
}

I have to write a Test Class in which I have to user runAs(userX){ inside of which I want static init block of above class should run.}

I have created below code in my TEST method:

        User LCRTestUser = Utils_TestMethods.createStandardUser('LCROwner');
        LCRTestUser.BypassTriggers__c = 'AP33;AP20;AP_Case_CaseHandlerCaseBeforeInsert;AP10;AP41'; 
        System.debug('LCRTestUser.BypassTriggers__c:'+LCRTestUser.BypassTriggers__c);
        //Insert LCRTestUser ;
        System.debug('UserInfo.getName():'+UserInfo.getName());
    system.runas(LCRTestUser) {
        Test.startTest();
        System.debug('runAs Started');
//        Test.startTest();
            System.debug('UserInfo.getName():'+UserInfo.getName());
                System.debug('Utils_SDF_Methodology.PAD_BypassTrigger:'+Utils_SDF_Methodology.PAD_BypassTrigger);

        Test.stopTest();

But still it is initializing with main user, Not the user which is in runAs().
            System.debug('UserInfo.getName():'+UserInfo.getName()); in TEST method is providing name of the user who is in runAs. Static init block is executing after runAs but before this debug and is considering actual user.

Can I do anything so that it will consider user mentioned in runAs in static initialization block?
Shashikant SharmaShashikant Sharma
Hi,

What is Utils_SDF_Methodology.PAD_BypassTrigger could you share the whole code of class Utils_SDF_Methodology
seven23seven23
[@Mak One] did you ever find a solution to this? I'm facing the exact same scenario. Thanks!