How to get Custom Settings in Apex Test code?

Just like normal SObjects, your Test Context doesn't have access to the custom setting records already in the database.

Preferred solution

You can perfectly, insert a new Custom Setting record, in your test context like you would normally do with an SObject

Whatever_custom_setting__c setting = new Whatever_custom_setting__c();
setting.Name = 'Test Setting';
setting.Value__c = 'Whatever';
insert setting;

and then your function should return the newly created test setting.

Alternative solution

declare your method with the @isTest(SeeAllData=true) that way your testmethod has visility over the data in your database, outside of the test context. However, these testmethods might fail in cases where there is no data in the custom setting.


The following worked for me.

The code that uses a token:

    Map<String, ServiceTokens__c> setting = ServiceTokens__c.getall();
    ServiceTokens__c token = setting.get('Token__c');                              
    String token = token.Token__c;

In the test setup method I have the following:

    ServiceTokens__c tokenCustomSetting = new ServiceTokens__c();         
    tokenCustomSetting.Name = 'Token__c';        
    tokenCustomSetting.Token__c = 'placholder';        
    insert tokenCustomSetting;

In the above code, the Name is the API Name that you see in your Custom Settings. Here is screenshot of my custom setting:

enter image description here