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

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

2 Answers 2

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

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

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 .

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;
// Perform some testing using the test records
  • yes,i am creating custom settings in test class.Is there any way we can allow the access to only the existing custom settings. Commented Oct 22, 2012 at 7:44
  • @VipulReddy No there is no other way that i am aware that we can give only acess to custom settings . Commented Oct 22, 2012 at 7:47
  • @VipulReddy Have updated my answer too.May be winter 13 if enabled in your ORG will save your time if the same works for custom setting Objects Commented Oct 22, 2012 at 8:03

I think your only option is to create the Custom Setting records at the start of the test class. In that way your code can find them during the test. That also allows you to create test scenarios where the custom settings vary.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .