Showing posts with label Test Class. Show all posts
Showing posts with label Test Class. Show all posts

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();

Content type not allowed for Test.loadData(): application/CSV

MIME Type (application/csv) in Static Resources:

If you create data of custom settings using a CSV file of Static Resource in test classes (@isTest) then the MIME Type column of that Static Resource should be ‘text/csv’ otherwise you will get an error in

Error : System.TypeException: Content type not allowed for Test.loadData(): application/csv