How to get Custom Settings in Apex Test code?

I have a custom setting used by a visual force page to load error messages based on a code value. In my test code for the page I have this statement

Integer howMany = Message__c.getAll().values().size();

I am calling the getall method to get the values one time from the custom setting and trying to find the size. It is returning me null which means that there is some limitation in using custom settings on a test method. Could some body tell me whether we can load all the values from custom settings on a test method? The scope of the custom setting is protected.


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.

Source : Link , Question Author : Buyan Thyagarajan , Answer Author : pjcarly

Leave a Comment