I am trying to setup test data for a test class. I want to do a loop and populate the trn.Training_Resource__c field with unique name, record ID from the trL Training_Resource__c object instead of hard coding a name ,'a1ZG000000CoOui' and then having to have multiple insert lines.

How to do it? BTW, is this the correct way to setup test data?


 List <Training_Resource__c> trL = New List<Training_Resource__c>();
    Integer x;
    for (x=1;x<3;x++)
        Training_Resource__c tr = New Training_Resource__c();
        tr.Name = 'Test'+x;
    insert trL;

    Training__c trn = New Training__c();
    trn.Name = 'A 1';

    Training__c trn2 = New Training__c();
    trn2.Name = 'A 2';
    insert trn;
    insert trn2;  

Dont hardcode your parent record id. Use the ids in the first list you inserted ie. Instead of hardcoded id, reference trL[0].id , trL[1].id etc.

  • Great. What about generating unique names for each test record? – Apex N-u-b Jun 2 '16 at 9:57
  • Just name them 'A ' + String.valueof(x); in your loop – CloudHugger Jun 2 '16 at 10:10

As an alternative

 List <Training_Resource__c> trL = new List<Training_Resource__c> {
       new Training_Resource__c(name = '00Test'),
       new Training_Resource__c(name = '01Test')};
 insert trL;

 List<Training__c> trnL = new List<Training__c> {
      new Training__c(name = 'A 1', training_resource__c = trl[0].id),
      new Training__c(name = 'A 2', training_resource__c = trl[1].id)};
 insert trnL;

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.