3

In my testing code, I wrote this piece of code to initialize an account list of size 3:

List<Account> acList = new List<Account>();
    for (integer i = 0; i < 3; i++) {
        Account ac = new Account();
        ac.type = 'Customer';
        ac.CountryArea__c = 'Australia';
        ac.Vertical_Market__c = 'Education';
        ac.T1_Industry__c = 'Other';
        acList.add(ac);
    }
    acList[0].Name = 'Test Account One';
    acList[1].Name = 'Test Account Two';
    acList[2].Name = 'Test Account Three';
    insert acList;

I believe this code will work. But it doesn't seem to be very elegant to me. By adding one Account to the account list every time will cause the list to resize (which means the list will probably destroy the old instance and allocate space for a larger one in background) every time will be of low efficiency. This is an array of 3 so will not be a big deal. But is there a better way to write this? Appending to a set will definitely increase efficiency, but will not allow me to use acList[0].

3 Answers 3

6

I don't think the efficiency of this is really a major concern, but you can just create the list in one hit:

List<Account> acList = new List<Account>
{
    new Account(Name = 'Test Account One', Type = 'Customer', CountryArea__c = 'Australia'),
    new Account(Name = 'Test Account Two', Type = 'Customer', CountryArea__c = 'Australia'),
    new Account(Name = 'Test Account Three', Type = 'Customer', CountryArea__c = 'Australia'),
};

insert acList;

Of course, this does mean more manual work but you were setting the name manually anyway (in those scenarios I usually just concatenate the i) when using a loop to create/init data.

2

Can you try this it helps for you

 List<String> acnames     = new List<String>{'One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen'};
List<Account> acList = new List<Account>();
    for (integer i = 0; i < 3; i++) {
        Account ac = new Account();
        ac.Name = 'Test Account '+acnames[i];
        ac.type = 'Customer';
        ac.CountryArea__c = 'Australia';
        ac.Vertical_Market__c = 'Education';
        ac.T1_Industry__c = 'Other';
        acList.add(ac);
    }
insert acList;
1

The answer LaceySnr is correct. If you want to populate data in your test methods without having to write many lines of code you can also use Test.loadData method and use Static resources as described in Loading Test Data

// Load the test accounts from the static resource
List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .