Loading Test Data
Using the Test.loadData method, you can populate data in your test methods without having to write many lines of code.
Follow these steps:
- Add the data in a .csv file.
- Create a static resource for this file.
- Call
Test.loadDatawithin your test method and 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:
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. To learn more about static resources, see “Defining Static Resources” in the Salesforce online help.
Once you create a static resource for your .csv file, the static resource will be assigned a MIME type. Supported MIME types are:
The following are steps for creating a sample .csv file and a static resource, and calling Test.loadData to insert the test records.
-
Create a .csv file that has the data for the test records. This sample .csv file has three account records. You can use this sample content to create your .csv file.
-
Create a static resource for the .csv file:
- From Setup, enter
Static Resourcesin theQuick Findbox, then select Static Resources. - Click New.
- Name your static resource
testAccounts. - Choose the file you created.
- Click Save.
- From Setup, enter
-
Call
Test.loadDatain a test method to populate the test accounts.