Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 551
Ben Dunlap Avatar asked Feb 06 '12 18:02

Ben Dunlap


People also ask

What is the recommended process for an Apex unit test?

Unit test methods take no arguments, commit no data to the database, and send no emails. Such methods are flagged with the @isTest annotation in the method definition. Unit test methods must be defined in test classes, that is, classes annotated with @isTest .

When creating unit tests in Apex which statement is accurate?

When creating unit tests in Apex, which statement is accurate? A. Unit tests with multiple methods result in all methods failing every time one method fails.

What percentage of Apex code must be executed by test methods?

You must have at least 75% of your Apex covered by unit tests to deploy your code to production environments. All triggers must have at least one line of test coverage. We recommend that you have 100% of your code covered by unit tests, where possible.


1 Answers

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.

like image 143
Jason Hardy Avatar answered Oct 12 '22 13:10

Jason Hardy