How to create Hierarchy custom settings in Apex

I need to create Hierarchy custom settings in my test class to avoid the seeAllDate = TRUE

Little confused on how to create Hierarchy custom settings. Looked at the docs and other questions but don’t see one on how to create in Apex:

Below is how I do for the List settings:

    custSettings__c settings = new custSettings__c();
    settings.Name = 'SF Environment Settings';
    settings.someField__c = 'Some Value';

    insert settings;


You can use either of the two following constructs:

insert new custSettings__c(SetupOwnerId=UserInfo.getOrganizationId(), SomeField__c='Some Value');


custSettings__c settings = custSettings__c.getOrgDefaults();
settings.SomeField__c = 'Some Value';
upsert settings custSettings__c.Id;

Either way, basically you need to make sure SetupOwnerId is set to the organization’s ID.

Source : Link , Question Author : javanoob , Answer Author : sfdcfox

Leave a Comment