You need to sign in to do that
Don't have an account?
getOrgDefaults() returning empty object/null when API >23.0
Hi there,
I was doing some end of project clean up and was bumping up the API versions on some of my classes when a test class started failing.
The reason was because once the API version was set to anything above 23.0, the getOrgDefaults() function would return an empty object, even though we had default values defined for the hierarchial custom setting we were referring to. If the API version was set to 23.0 or lower, the values would be returned as expected. I tried this with out other custom setting objects and got the same results.
Running a getOrgDefaults() in execute anonymous doesn't produce the same results, the object is returned as expected.
Anybody else experiencing something similar? We can leave the API version for this class alone for now, but it's still disconcerting and may prove problematic as time goes on.
A little digging around and I came across this blog post: http://www.tgerm.com/2010/03/custom-settings-null-pointer-exception.html
There's a snippet in there that shows you how to create the defaults, by setting the "SetupOwnerId" of the custom setting to the id of your Org.
upsert new MyCustomSetting__c (SetupOwnerId = Userinfo.getOrganizationId(), Field1__c = X, Field2__c = Y, ....);
So, lesson learned, recreate your custom settings when testing. :P
All Answers
Nevermind, I *think* figured it out, I didn't realize that the default values for your Custom Settings are considered existing data. That is, Test classes aren't allowed to see an org's existing data and test classes should create their own, and existing data *includes* anything you've set up in the Custom Settings. Or at least I think that that's what's happening, 'cuz getOrgDefaults() only returns an empty object when doing tests.
Interesting, can't believe I hadn't run into this until now...
EDIT: So....how *does* one set org defaults programmatically while running test classes?
A little digging around and I came across this blog post: http://www.tgerm.com/2010/03/custom-settings-null-pointer-exception.html
There's a snippet in there that shows you how to create the defaults, by setting the "SetupOwnerId" of the custom setting to the id of your Org.
upsert new MyCustomSetting__c (SetupOwnerId = Userinfo.getOrganizationId(), Field1__c = X, Field2__c = Y, ....);
So, lesson learned, recreate your custom settings when testing. :P
Old post, but still usefull!
decimal myValue = MyCustomSetting__c.getInstance().myCustomField__c;
if (myValue == null) {
system.debug('myCustomField__c is null ');
upsert new MyCustomSetting__c(myCustomField__c = 20.0);
}
myValue = MyCustomSetting__c.getInstance().myCustomField__c;