Loading Test data using CSV (Static Resource)

Writing Test classes is a regular activity for developers. While writing test classes, usually developers end up creating the same data again again. To minimize these efforts, to create data in bulk and make data creation easier, Salesforce provides a better approach.

Using Test.loaddata(), you can load test data in your Test classes. To do that, you need to follow these steps:

  1. Add data in csv file.
  2. Load CSV files, in static resource.
  3. Call Test.loadData within your test method and passing it the sObject type token and the static resource name.
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');

The CSV file contains data in a comma separated format. While preparing the file, the first line must contain field names of the sObject.

@isTest
private class testDataUtil {
static testmethod void testLoadData() {
// Load the test accounts Data from the static resource
List listAccs = Test.loadData(Account.sObjectType, ‘testAccounts’);

    // Get test account
    Account a1 = (Account)listAccs[0];
    String acctName = a1.Name;
    System.debug(acctName);

}

}