+ Start a Discussion
M-HM-H 

Test Class System.ListException: List index out of bounds: 0

Hi Every1,

 

I know many of you might seen this error before.

 

Failure Message: "System.ListException: List index out of bounds: 0", Failure Stack Trace: "Class.UserGroupTest.testuseradd: line 22, column 1"

 

Can someone help me resolve this perticular error. 

 

 

 

@istest
class UserGroupTest {

static testmethod void testuseradd(){

    test.starttest();
    List<Account> a= [Select Id From Account Where Name LIKE 'ABC%' Limit 1];

    List<Contact> c1 = [Select Id From Contact Where AccountId=:a[0].Id];
    
    List<Profile> p = [Select Id From Profile Where Name='** Custom: Portal: XYZ Partner'];
    
    if (p.size() > 0) {
        User u = new User(Username='test@teest.org',
         LastName='My Test',
          Alias='mmtt',
           CommunityNickname='tt11',
            TimeZoneSidKey='America/Los_Angeles',
             LocaleSidKey='en_US',
              EmailEncodingKey='UTF-8',
               LanguageLocaleKey='en_US',
               IsActive=true,
                ContactId=c1[0].Id, ProfileId=p[0].Id, email='test@teest.org');
        insert u;
    }
    test.stoptest();
    
    }
}

Rahul SharmaRahul Sharma
Before refering to the 0th index of list you must perform a check on whether the list is empty or not. Whenever you try to access records from list first check if its empty or not like it is done below: List lstAccount = new List(); // Fill the list... // Before processing the list check if its empty or not // It will go inside the loop only if the List is having values in it. if(lstAccount.size() > 0){ // Do something with lstAccount[0].Name }
hemant037hemant037

when you declare the list than declare it like this

 

List<String> test=new List<String>();

 

than use test List...

test=[select ------];

 

Thanks.

Rahul SharmaRahul Sharma

Yes Hemant partially is correct.

 

Always before accessing the list, you must check for whether list is empty.

 

An example here would make more sense :

 

List lstAccount = [Select Id, Name from Account Limit 10];

// Before processing the list check if its empty or not
// It will go inside the loop only if the List is having values in it.
if(lstAccount.size() > 0) {
    // Do something with lstAccount[0].Name
}

// If you try to access lstAccount[0] without empty check then it will obviously throw that error!!

 

hemant037hemant037

ya Rahul you are right. 

and please if possible from next time highlight the line where are you getting error.

like in this code  line 22 containing error so please highlight it in code.


Thanks