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
Balu_SFDCBalu_SFDC 

Writing the test class

Hi everyone.....

i am new to the apex Test class..so plz help me on for writing the test class for below code

 

trigger autonumber1 on Account (before insert)
{
  for(account a:trigger.new)
  {
  
    List<account> ac=[select autonumber__c from account];
 if(ac[0].autonumber__c!=null)
  {
  a.autonumber__c=ac[0].autonumber__c+1;    
   }
   else
   a.autonumber__c=1200;
}
}

 

i am getting 60% code coverage but i got the failure message like...

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, autonumber1: execution of BeforeInsert caused by: System.ListException: List index out of bounds: 0 Trigger.autonumber1: line 7, column 1: []

 

 

thanks in advance...

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
nickwick76nickwick76

So you got the 'list index out of  bounds: 0' when running the test class?

 

One thing could be that you have not created any test accounts to query. By default test classes no longer can query the org data. You have to create it the test data yourself.

In this case I would recommend this. In other cases if you need to query org data you can do that using the notation @isTest (SeeAllData=true)

 

HTH

// Niklas

All Answers

nickwick76nickwick76

So you got the 'list index out of  bounds: 0' when running the test class?

 

One thing could be that you have not created any test accounts to query. By default test classes no longer can query the org data. You have to create it the test data yourself.

In this case I would recommend this. In other cases if you need to query org data you can do that using the notation @isTest (SeeAllData=true)

 

HTH

// Niklas

This was selected as the best answer
SammyComesHereSammyComesHere

Put @seeAllData and put a check before you operate on a list as 

 

if(ac !=null and ac.size()>0)

 

because it may be possible that your query doesnt give any results even after @seeAllData . better handle it :)

 

 

lovetolearnlovetolearn

Hi, 

 

Not entirely sure what you are trying to accomplish with your code since your query for the List does not have a WHERE clause. Also, you will probably run into a SOQL governor limit error since you have a SOQL query inside your for loop. 

 

I am going take a blind stab, try the following test class: 

@isTest

private class testautonumber(){
	static testMethod void testNumber(){
		Account a = new Account();
		a.Name = 'Test Account';
		a.autoNumber = 123; //assuming that the "autonumber" field is an integer type field. 
		insert a;
		Account a1 = new Account();
		a1.Name = 'Test Account';
		insert a1;
		
		a1.Name = 'Test Account updated'
		update a1;
	}
}

 

Balu_SFDCBalu_SFDC

thax for your reply.

but it's not working....