Saturday, February 28, 2015

Use Static Resources to create data in Test Classes (@isTest)

Use Static Resources to create data in Test Classes (@isTest)

Example 1:
// Test data preparation (from CSV file store in Static Resource)
// Load test data from static resource CSV into the DB
List<sObject> ls = Test.loadData(Account.sObjectType, 'myCsvResource');

Example 2:
// Test Data Factory class
@isTest
public class TestDataFactoryUtil{
    public static List<Custom_Setting__c> createCustomSettingValues(){
    // Create a sample .csv file "CustomSettingValues" and save it in Static Resource
    List<Custom_Setting__c> customSetting = Test.loadData(Custom_Setting__c.sObjectType,       'CustomSettingValues');
    return customSetting;
   }
}

// Main Test Data that is using Test Data Factory class
// Create records of custom setting "Custom_Setting__c"
List<Custom_Setting__c> customSettingValues = TestDataFactoryUtil.createCustomSettingValues();