You need to sign in to do that
Don't have an account?
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;
} }
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
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
Thanks Niket.
The query does return value and it is used on associated VF page. the array/List is certainly not empty.
Thanks.
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!!
Hi Pranav ,
Could you please paste your test class code ?
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.
Good to hear. :-)
FYI, this occurs because you cannot access your real data from a test class:
http://stackoverflow.com/questions/9164986/how-do-i-avoid-standard-price-not-defined-when-unit-testing-an-opportunitylineit