I am using a util class with a singleton pattern to retrieve the custom settings. Like below:

private static Additional_System_Settings__c addSysSetting;

public static Additional_System_Settings__c getAdditionalSystemSetting() {
    if(addSysSetting == null) {
        addSysSetting = Additional_System_Settings__c.getInstance(UserInfo.getUserId());

    return addSysSetting;

The only thing I am worried about is I am using the current user's user info to retrieve the related custom setting which means if in the test environment if I have System.runas() in my code and has that custom setting variable initialised before the system.runas() part, the runas() section will be probably be using the previous user's setting.

I am not quite sure that in this scenario, since these are run under two user's identities, will that be running in two different execution context or not? And should I be worried about this at all?

1 Answer 1


The variables/heap/etc are not reset when System.runAs is encountered. As such, your code could run in to wrong settings (that of the admin/test runner instead of test user). If you don't care about the settings returned, you can ignore this. If you need a specific value, and cannot verify the value hasn't been tampered with by accident, just make it @TestVisible and modify it as you need:

// NOTE: this variable is used in the XYZ unit test
@TestVisible static Additional_System_Settings__c addSysSetting;


System.runAs(u) {
  insert new Additional_System_Setting__c(SetupOwnerId=UserInfo.getUserId(), ...);
  // Clear any previous value...
  SomeClass.addSysSetting = null;
  // ...

Obviously, you should avoid overusing @TestVisible, but there are times when usage is unavoidable, and this may very well be a good use for this annotation. Make sure you comment the variable so future developers know why it is marked @TestVisible.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .