5

I have a situation where I was querying standard pricebook with SeeAlldata=true in test class.

Pricebook2 pb2 = [select Id, Name, IsActive from PriceBook2 where IsStandard=True LIMIT 1];

Later I changed SeeAlldata=false and getting the id like this:

Id pricebookId = Test.getStandardPricebookId();

Now I'm executing a method from test class in which I'm querying standard pridebook. I cannot use the Test.getStandardPricebookId(); in apex class.

How can I fix this issue without setting SeeAlldata=true.

  • 1
    in that method put a condition like if(Test.isrunningtest()) { Id pricebookId = Test.getStandardPricebookId();//Return getStandardPricebookId } else { Pricebook2 pb2 = [select Id, Name, IsActive from PriceBook2 where IsStandard=True LIMIT 1]; //return query id } – Ratan Paul Feb 25 '16 at 17:44
9

From my Util.cls library ...use a consistent entry point for fetching the StandardPricebookId across testmethods and PROD code

private static Pricebook2 stdPriceBook;  // Singleton, remember when first referenced

//  ------------------------------------------------------
//  getStdPricebookId : as of V31, testmethods can locate std pricebook wo seeAlldata=true
//  ------------------------------------------------------
public static ID getStdPricebookId() {
    if (Test.isRunningTest())   return Test.getStandardPricebookId();
    return getStdPricebook().id;    
} 

//  -------------------------------------------------------
//  getStdPriceBook: Singleton
//  -------------------------------------------------------
public static Pricebook2    getStdPriceBook () {
    if (stdPriceBook == null) 
        stdPriceBook    = [select id, name from Pricebook2 where isStandard = true limit 1];
    return stdPriceBook;    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.