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
Amit Chaudhary 7Amit Chaudhary 7 

List index out of bound error ?

Same code works in anonymous window but in test class it shows list index out of bound error .

@istest

public class setMethod{
 
    public static testmethod void main(){
        
        List<student__c> sts = new List<student__c>();
  sts =[select name from student__c ] ;
        
        
           string temp = sts.get(2).name ;
     
        system.debug(temp);
    }    
}
CheyneCheyne
You cannot see all of your org's data from within a test class, so you have to create some student records before your query will return anything.

Student__c student = new Student__c(Name='test');
insert student;
Student__c student2 = new Student__c(Name='test2');
insert student2;

List<Student__c> sts = [SELECT Name FROM Student__c];
srlawr uksrlawr uk
Cheyne is spot on, you cannot access "existing" data from code running in testMethods (since API 24.0 ) therefore best practise dictates that you "create" the data your test methods need before attempting to work with it. You can rest assured no information is stored to the database doing this, and so no record limits or data protection issues are likely to come into play.

An alternative way to circumnavigate this issue is to mark your testClass with the @isTest(SeeAllData=true) flag, which grants the original level of access to your test class. (This is often not considered best practise though as it makes your test passing dependant on data that may be changed or removed). It can provide a quick fix, or help (short term) test particulally complicated data structures.

Lots more info on this can be found in the developer docs here.
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_annotation_isTest.htm