How do I avoid STANDARD_PRICE_NOT_DEFINED when unit-testing an OpportunityLineItem in Apex v24.0?

Ben Dunlap picture Ben Dunlap · Feb 6, 2012 · Viewed 17k times · Source

Apparently a new feature of the Spring '12 / v24.0 release of Apex in Salesforce.com is that unit tests no longer have access to 'real' data -- thus (if I'm understanding the change correctly) a SOQL query will now only retrieve objects that have been inserted during the course of the unit test -- and even that is subject to some limitations.

At any rate this seems to throw OpportunityLineItem testing out the window, because:

  • It's impossible to insert an OpportunityLineItem without a PriceBookEntryId, BUT
  • You can't insert a new price-book entry for product X unless you already have a Standard Price Book entry for product X, BUT
  • There isn't a Standard Price Book in the test data because the Pricebook2 table, like all tables, is effectively empty at the beginning of the unit-test run, AND
  • There's no way to create a Standard Price Book in Apex

I'm really hoping I got at least one of those four points wrong, but so far no variation on my existing unit-tests has shown any of them to be wrong. Which of course means my unit tests no longer work. This happened literally overnight -- the tests ran fine in my sandbox on Friday, and now they fail.

Am I missing something, or is this a bug in the new SFDC release?

Answer

Jason Hardy picture Jason Hardy · Sep 17, 2014

There is new functionality introduced in Summer 14, you can now use Test.getStandardPricebookId() to get the standard pricebook ID without having to set SeeAllData to True.