[SalesForce] Test Data – Static Resources

I have many custom objects with lots of relationships and i want to create some test data for my test classes. For example, i have the Objects
Account
Opportunity
Basket
Product Configuration
Product Definition
Attribute

What is the best way in order to create test data for those Objects. I am thinking to do the following:

  1. Create test data in csv files for each object as independent records
  2. Upload the files as static resources in my sandbox
  3. Inside my test Apex class load the Accounts static resource
  4. Then, load the opportunities static resource and after loading them, set the Accounts as parents and update the opportunities.
  5. Load the bsaket data and set the opportunity id field to the respective opportunities.

Is this a best practice? Is there maybe a "quicker" road to this?

Best Answer

Salesforce provides the Test.loadData method that leverages static resource CSV files to load data for specified SObject types which will do what you need.

Part of the problem you will face if you do try to use CSV static resources is making relationships between these objects without introducing an external ID field just for testing.

I would say that we don't take this approach and instead have explicit code (marked as @IsTest) to handle creating test data (this being one or more "test data factory" with varying responsibilities in terms of data creation). It is more verbose but keeps all test-specific materials in one place - test apex - and simplifies creating hierarchies of objects.

Related Topic