+ Start a Discussion
SFDC HedgehogSFDC Hedgehog 

Multiple Pricebook issue with test class

I have a test class that that is inserting a product into the standard pricebook.
Relevant code:
Id pricebookId = Test.getStandardPricebookId();

Product2 prd1 = new Product2 (Name='Test Product Entry 1', Description='Test Product Entry 1',productCode = '99999', isActive = true);
insert prd1;

PricebookEntry pbe1 = new PricebookEntry (Product2ID=prd1.id, Pricebook2ID=pricebookId, UnitPrice=50, isActive=true);
insert pbe1;
Next, in the trigger, I can have the same product code in multiple pricebooks, so I have to check to see if the product
is from the standard pricebook.  Again, relevant code;
thePbe = [SELECT id, Product2Id, Pricebook2.IsStandard, Pricebook2.Id  
                   FROM PricebookEntry 
                   WHERE  IsActive = true AND Pricebook2.IsStandard=true 
                   AND Product2Id IN (SELECT Id FROM Product2 WHERE ProductCode = '99999' And isActive = True) ];
This returns zero rows - which I thought was weird.  So, in the trigger I queried the price books like this;
List<PricebookEntry> pbe =  [SELECT id, Pricebook2.IsStandard, Pricebook2.Id  from PricebookEntry WHERE  IsActive = true ];
System.debug('pbe.size(): ' + pbe.size());    // Prints "1"

if(pbe.size() > 0)
     System.debug('pbe[0].Pricebook2.IsStandard: ' + pbe[0].Pricebook2.IsStandard);
This prints "false" (!)

In other words - I don't see why SFDC would give us the ability to get and set the "StandardPricebookId" - yet when queried, it is not the standard pricebook.    Obviously, I don't want to use Seealldata=true.   

Is there a way around this?   Does anyone see anything wrong?

The Test.getStandardPricebookId(); is confusing because it only gives you access to the standard Pricebook ID... it doesn't actually make the PB2 object visible to your test, so in your SOQL queries where you include PriceBook2.<field> it will fail. 

There is a more detailed explanation here:

You just need to change the way you are buliding your queries a little bit, to avoid directly querying the Pricebook2 object.