By utilizing the Test.loadData method, you can effortlessly input data into your test methods, eliminating the need for extensive code. Just follow these steps:
- Populate the data in a .csv file.
- Establish a static resource for the aforementioned file.
- Invoke Test.loadData within your test method, providing it with the sObject type token and the name of the static resource.
For instance, if you’re dealing with Account records and the static resource is named myResource, make the following call:
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');
The Test.loadData method provides a list of sObjects corresponding to each inserted record.
Prior to invoking this method, it is imperative to create the static resource. The static resource takes the form of a comma-delimited file with a .csv extension. This file encompasses field names and values for the test records, with the first line containing field names and subsequent lines containing the respective field values. For additional information on static resources, refer to the “Defining Static Resources” section in the Salesforce online help.
Once you’ve established a static resource for your .csv file, it will be assigned a MIME type. Supported MIME types include:
- text/csv
- application/vnd.ms-excel
- application/octet-stream
- text/plain
Example of Test.loadData
Here are the steps to generate a sample .csv file, establish a static resource, and employ Test.loadData to insert the test records.
- Generate a .csv file containing the data for the test records. This example .csv file includes three account records. You can utilize the provided sample content to craft your .csv file.
Name,Website,Phone,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry sForceTest1,http://www.sforcetest1.com,(415) 901-7000,The Landmark @ One Market,San Francisco,CA,94105,US sForceTest2,http://www.sforcetest2.com,(415) 901-7000,The Landmark @ One Market Suite 300,San Francisco,CA,94105,US sForceTest3,http://www.sforcetest3.com,(415) 901-7000,1 Market St,San Francisco,CA,94105,US
Establish a static resource for the .csv file using the following steps:
- Navigate to Setup, enter “Static Resources” in the Quick Find box, and select Static Resources.
- Click on the “New” button.
- Assign the name “testAccounts” to your static resource.
- Select the file you previously created.
- Click “Save.”
After creating the static resource, invoke Test.loadData within a test method to populate the test accounts.
@isTest 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; System.debug(acctName); // Perform some testing using the test records } }