How to access custom settings in test class without using the seealldata?

I want to use a custom settings inside a test class, without using the

SeeAllData=true
  • What are the options I have?
  • How can I accomplish it with a reasonable solution?

Answer

list<SFA_ContactFields__c> lstContacts=new   list<SFA_ContactFields__c>();//bulk List of custom setting object for bulk insert

 SFA_ContactFields__c csContactFields=new SFA_ContactFields__c(); //Custom Setting for Contact Fields
csContactFields.Name='CreatedDate';//Static record 1 of custom setting
lstContacts.add(csContactFields);

SFA_ContactFields__c csContactFields1=new SFA_ContactFields__c(); 
csContactFields1.name='IsDeleted';//Static Record 2 of custom settings
lstContacts.add(csContactFields1);

insert lstContacts;

Custom settings are nothing but an object .All you need in Test Class is instantiate the custom settings object and create the records of the custom settings and insert it in Test class itself.Make sure you bulkify your insert call.

Another quick approach is we definately keep the CSV of the extracted data from the Custom setting Objcet for migration purpose and then probably upload the same in static resource and reference the same in your Test class as per winter 13 documentation.

I have not tried the same that same holds good for custom settings too but you can try this one .

@isTest
private class DataUtil {
static testmethod void testLoadData() {
// Load the test accounts from the static resource
List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');
 // Verify that all 3 test accounts were created
 System.assert(ls.size() == 3);
 // Get first test account
Account a1 = (Account)ls[0];
 String acctName = a1.Name;
System.debug(acctName);
// Perform some testing using the test records
 }
}

Attribution
Source : Link , Question Author : Keepcalmncode , Answer Author : Mohith Shrivastava

Leave a Comment