How to Use Test.loadData in Apex Salesforce?

While writing unit tests in Salesforce Apex keeping your test code clean and maintainable is key. That’s where loadData comes in – a powerful method which loads test data from the csv file stored as static resource.

In this article we will learn how to use Test.loadData in Apex with simple example.

What is Test.loadData?

It is a built-in method in the Apex test Class. It helps you load records from the csv file stored as static resource.

Let’s have a look at the syntax.

List<sObject> records = Test.loadData(sObjectType, 'ResourceName');

sObjectType: the type of the record you are loading like Account.sObjectType.

ResourceName: the name of your static resource without csv extension.

Let’s have a look at complete example. First of all we need to create a CSV file and save it as static resource.

Name,Industry,Phone
Acme Inc,Manufacturing,1234567890
Globex Corp,Technology,0987654321

Save this file and upload it to Static Resources in Salesforce Setup. Name it TestAccounts.

Now let’s write the Apex code using Test.loadData() method.

@isTest
public class AccountTest {

    @isTest
    static void loadAccountsTest() {
        List<Account> accounts = (List<Account>) Test.loadData(Account.sObjectType, 'TestAccounts');
        
        System.assertEquals(2, accounts.size());
        System.assertEquals('Acme Inc', accounts[0].Name);
    }
}

Now your test method looks cleaner and your test data stays in a centralized place.

Why Use Test.loadData?

  • Keeps test data separate from test logic
  • Reusable across multiple test methods/classes
  • Great for large datasets
  • Reduces clutter and improves code readability

We hope now you know How to Use Test.loadData in Apex Salesforce. If you have any doubts then let us know in the comments below.

Leave a Comment