function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pranav_VaidyaPranav_Vaidya 

Apex class - List Index out of bound error

Hi,

 

Below is my Apex class. When I use this on my VF page there are no errors. However when I test run this from a test class I get error System.ListException: List index out of bounds: 0

Can you please point me what is going wrong here.

 

Thanks.

 

 

public class MyBudgetSnapShot {

 List <Travel_budget_cost__c> myBud = [Select Asset_class_Travel_Budget__c,Travel_budget_actual__c, Travel_budget_cost__c,Travel_budget_forecast__c
                               from Travel_budget_cost__c where id = 'a00s000Fc1Qt'];                              

 string strUserRoleId = UserInfo.getUserRoleId();
 UserRole usr= [Select Id,Name from UserRole where Id= :strUserRoleId];
 String strUserRole =usr.Name;
//****************    
 public string getAssetClassName(){
   List <Asset_class__c> CurrAstCls=[Select Name from Asset_class__c where Id = :myBud[0].Asset_class_Travel_Budget__c ];   -->This line is pointed as error
  return CurrAstCls[0].Name;
 } }

NiketNiket

Hi ,

 

You are getting this error in test class because in your test scenario , 

 

List <Travel_budget_cost__c> myBud = [Select Asset_class_Travel_Budget__c,Travel_budget_actual__c, Travel_budget_cost__c,Travel_budget_forecast__c
                               from Travel_budget_cost__c where id = 'a00s000Fc1Qt'];              

 

is not returing anything the list myBud is empty. Please check if the query returns any record or not ??

 

Please mark it as the solution if it answers your question so that others can also take benifit. 

 

Ckeck My Blog


Rajesh SriramuluRajesh Sriramulu

Hi

 

can u paste the below code  in test class where the error

 

 List <Asset_class__c> CurrAstCls=[Select Name fro

m Asset_class__c where Id = :myBud[0].Asset_class_Travel_Budget__c limit 1 ];

 

if it again get error means u can chage the limit value

 

let me know any issue

 

 

SRS

Pranav_VaidyaPranav_Vaidya

Thanks Niket.

 

The query does return value and it is used on associated VF page. the array/List is certainly not empty.

 

Thanks.

Pranav_VaidyaPranav_Vaidya

Thanks for your suggestions.

 

The query you mentioned is part of my main class. In the 'Test class' I am just calling the method which had this query and returns the result. And it works pefect when ran independent, the associated VF page shows results from this query.

 

Not sure what is going wrong!!

NiketNiket

Hi Pranav ,

 

Could you please paste your test class code ?

Pranav_VaidyaPranav_Vaidya

Hi,

 

I am able to fix this error by addin a validation to my class like below

 

if(myBud.size() > 0){

  // code goes here....

} else{

  // code here

 

}

 

Thanks for all your help.

NiketNiket

Good to hear. :-)

craigmhcraigmh