I have an object with a required lookup field. I want to use Test.loadData() to load hundreds of records from a CSV for unit testing for this object, but I want the unit test to be portable, meaning I can't hardcode the lookup Id.

This seems like an extremely common scenario, but I've had little luck finding any solutions to this scenario. Do I have to generate different CSV files for different orgs, or is there something obvious I'm missing?

As an example, how could I load User records from a CSV, given that ProfileId is a required field?

  • is this a managed package use case? or a multi-sandbox within one PROD org use case? – cropredy Jul 19 '16 at 4:39
  • @cropredy - I have many potential use cases, including a managed package and a multi-sandbox org. – JDB still remembers Monica Jul 19 '16 at 5:20
  • Well, with pre-existing Profiles, in a multi-sandbox org, the ProfileIds will all be the same in each sandbox – cropredy Jul 19 '16 at 14:39
  • Thanks. Another example may have been better... I was asking in the general case. – JDB still remembers Monica Jul 19 '16 at 14:40
  • the undocumented load behavior works well for many use cases, but won't on references to data not being loaded (i.e. ProfileId) -- sorry to focus on that. – cropredy Jul 19 '16 at 14:53

Currently there is no such support in Test.loadData() to handle complex lookups and Master detail.

But there is one idea on idea exchange that you can vote for.


Meanwhile a workaround will be create a replica of Test.loadData() in APEX. ie read from static resource in your test class and provide logic to replicate the records via your normal DML statements. I know its tedious and ugly. But when facing huge data crises during tests,this was the approach we finalized.

There is Also an Undocumented behavior of test.loadData that you can use to populate relationships. Yes it works miraculously but we don't know when salesforce will stop supporting it.

Test.loadData() - undocumented (but useful) behavior loading relationships

  • Elaborate how this helps specific example of OP - loading User records with lookup to Profile across many orgs – cropredy Jul 19 '16 at 4:38
  • 1
    @cropredy - User was one example I ran into, but it's not the only case where I have a required field. I think this answer sums things up for me. It confirms my suspicions, at least. – JDB still remembers Monica Jul 19 '16 at 5:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.