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
YongChenYongChen 

SOQL in Apex test class

Hi,

The following code gives me different results when run it in test class.
Pricebook2[] standardPB = [Select Id From Pricebook2 where IsStandard = true];
System.debug('standardPB = '+standardPB.size());

When include this in test class, it gives me: "standardPB = 0" where in Execute Anonymous, it gives me "standardPB = 1". 

I have the following code in my trigger, which gives me "List index out of bounds" when running test class.
String standardPBId = [Select Id From Pricebook2 where IsStandard = true][0].Id;
Could someone explain it?

Thanks,
 
Best Answer chosen by YongChen
Shaijan ThomasShaijan Thomas
Hi YoungChen,

You have to use seeAllData= true in your test class.

Thanks
Shaijan Thomas

All Answers

KaranrajKaranraj
YongChen - In test class you will get data only you have created in the test class. You can't create StandardPrice book record in test class and using seeAllData= true is not recommended approach in apex class because it will access the org data, there is chance to test class failure or it will show different code coverage in different org and time when the data is not avaiable in your org. 

To get the standard pricebook Id in your test class use the below code, which will get the without using seeAllData=true in your test class.
Id pricebookId = Test.getStandardPricebookId();
To know more about pricebook entry check this link - http://docs.releasenotes.salesforce.com/en-us/summer14/release-notes/rn_apex_price_books_in_tests.htm
 
YongChenYongChen

Hi Karanraj,

Thank you for the reply. 
"Test.getStandardPricebookId()" works great in test class, but the problem is, the following code in my trigger class (not my test class)  throws "List index out of bounds" WHEN running test calss.
 

String standardPBId = [Select Id From Pricebook2 where IsStandard = true][0].Id;
Thanks,
Shaijan ThomasShaijan Thomas
Hi YoungChen,

You have to use seeAllData= true in your test class.

Thanks
Shaijan Thomas
This was selected as the best answer