0

I've a simple trigger on account, which on update, create a new contact with firstname ='abc' and lastname = 'xyz'

It is giving error

list index out of bounds

when I using system.assert statement.

Can't I query contact inserted through trigger in my test class?

Pls see below

@isTest

public class InsertContactTest
{
   public static List<Account> accNew  = new list<Account>();

   public  static void CreateTestData()
   {
     createTestAccount();
     UpdateAccountCreated();
   }

  static void createTestAccount()
  {
  Account Acc = new Account(); 
  acc.Name = 'My new Account1'; 
  acc.Type= 'Prospect'; 
  AccNew.add(Acc);

  Account Acc1 = new Account(); 
  acc1.Name = 'My new Account2'; 
  acc1.Type= 'Technology Partner'; 
  AccNew.add(Acc1);

 insert accNew;


}

  static void UpdateAccountCreated()
  { 
    AccNew[0].Industry = 'Banking';
    AccNew[1].Industry = 'Agriculture';
    update AccNew;
  }




testMethod  static void  TestTriggerCreateContact()
   {
  CreateTestData();

 test.startTest();

 List<contact> Conlist= [select id, firstName, lastName from contact where AccountID = : AccNew]; // Can I query this or not ?

 test.stopTest();
 system.assert(conlist[0].firstName == 'ABC');//Error on this line- list index out of bounds
system.assert(conlist[0].lastname == 'XYZ');

1 Answer 1

0

You're getting an error because your trigger didn't actually create any new contacts, so the list is empty (thus, "index is out of bounds"). You can bind a list of SObjects to a query filter, which is the same effect as extracting all of the "ID" field values and using that in the query, without the penalty incurred by actually iterating over the list and extracting the values (e.g. less time used, less memory used, etc). Without seeing your source code for the trigger, we don't know what's wrong, but we can definitely state that your trigger is not working as designed, otherwise the contact would exist, and would be queried in your test method.

2
  • You can have the same error, in your method updateAccountCreated(), Because your accounts can't be created
    – Torsen
    Feb 2, 2015 at 7:38
  • SFDCfox- thanks! great input... somebody has edited trigger and I didn't notice Feb 2, 2015 at 9:01

You must log in to answer this question.

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