Wednesday, 14 November 2012

Loading Test Data from Static Resources

Loading Test Data from Static Resources

Using the new Test.loadData method, you can populate data in your test methods without having to write many lines of code. Simply, add the data in a .csv file, create a static resource for this file, and then call Test.loadData within your test method by passing it the sObject type token and the static resource name. For example, for Account records and a static resource name of myResource, make the following call:
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');

The Test.loadData method returns a list of sObjects that correspond to each record inserted.

You must create the static resource prior to calling this method. The static resource is a comma-delimited file ending with a.csv extension. The file contains field names and values for the test records. The first line of the file must contain the field names and subsequent lines are the field values.

Once you create a static resource for your .csv file, the static resource will be assigned a MIME type. Supported MIME types are:

Test.loadData Example

The following are steps for creating a sample .csv file and a static resource, and calling Test.loadData to insert the test records.
1.       Create a .csv file that has the data for the test records. This is a sample .csv file with three account records. You can use this sample content to create your .csv file.

sForceTest1,,(415) 901-7000,The Landmark @ One Market,San

sForceTest2,,(415) 901-7000,The Landmark @ One Market Suite
300,San Francisco,CA,94105,US
sForceTest3,,(415) 901-7000,1 Market St,San Francisco,CA,94105,US

2.       Create a static resource for the .csv file:
a.       Click Your Name > Setup > Develop > Static Resources, and then New Static Resource.
b.      Name your static resource testAccounts.
c.       Choose the file you just created.
d.      Click Save.
3.       Call Test.loadData in a test method to populate the test accounts.

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

No comments:

Post a Comment

Why to use Database.Stateful()?

Database Stateful is interface. It is used in batch classes to maintain the state of the class across transactions i.e. if you want to use ...