0

I have a hierarchy type custom setting with org level defaults and no user or profile override values. I have changed the org level value for one field, but in my APEX tests, the code still retrieves the previous value and not the new value.

I understand the values are cached and it doesn't appear there's a way to expire or reset this cache. Here's what I tried:

  1. Changed the field value
  2. Removed the field value
  3. Removed the org level default value record itself

After doing these three things, the custom settings field value is still the previous value, and not the current value. Here's how I am accessing it in my test:

String setting = My_Custom_Settings__c.getInstance().My_Custom_Setting_Field__c;

I would expect (and thought I have seen) that the cache would reset when the values changes, but that doesn't appear to be happening.

0

I forgot that custom settings values were setup like regular test data. I needed to change the test data setup code for the change to take affect in the test class. Once I changed the test code setup, the new value took affect.

0

Data is cached meaning it does not need to be retrieved via DML.

However based on your code the value will always be the latest committed values so if you are not performing DML once you make a change it will not be reflected.

The following works just fine...

@isTest
public class myExampleTest{

    @TestSetup
    public static void createCustomSetting(){
        My_Custom_Settings__c tmp = My_Custom_Settings__c.getInstance( UserInfo.getOrganizationId());
        tmp.My_Custom_Setting_Field__c = '123';
        insert tmp;
    }

    public static testmethod void myexample(){
        My_Custom_Settings__c tmp = My_Custom_Settings__c.getOrgDefaults();

        system.assertEquals('123',tmp.My_Custom_Setting_Field__c);

        tmp.My_Custom_Setting_Field__c = '456';
        update tmp;

        tmp = My_Custom_Settings__c.getOrgDefaults();
        system.assertEquals('456',tmp.My_Custom_Setting_Field__c);
    }



}

If you want to NOT do DML after making the change you need to perform some caching of your own like so:

String setting{

   get{
       if(setting == null)
           setting = My_Custom_Settings__c.getInstance().My_Custom_Setting_Field__c;

        return setting;

   }

    set;
}

Then if you change the value without performing DML it will be reflected in your variable and not retrieve the current committed values

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.