[SalesForce] Get standard price without query? SeeAllData cannot be true

I am getting this error in my test class with pricebook entries and products:

System.DmlException: Insert failed. First exception on row 0; first error: STANDARD_PRICE_NOT_DEFINED, No standard price defined for this product: []

I've seen many solutions using a query for standard pricebook, but I don't want to use that, because SeeAllData needs to be true for it to return anything, and that messes up the rest of the test class. Suggestions?

ID standardPBID = Test.getStandardPricebookId(); 
    List<Pricebook2> standardPB = [select id from Pricebook2 where isStandard=true];
    System.debug('Standard Pricebook found?');
    System.debug(standardPB.size() > 0); // false
    Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
    insert customPB;

    Product2 elderProd = new Product2(IsActive = true, Name = 'Elder Gifts');
    insert elderProd;
    PricebookEntry elderPBE = new PricebookEntry(
        Pricebook2Id = customPB.Id, Product2Id = elderProd.Id,
        UnitPrice = 0, IsActive = true, UseStandardPrice = true);
    insert elderPBE;

Best Answer

Try the following code. Here you can see we insert a price book entry for the standard price book.

Product2 elderProd = new Product2(
        IsActive = true,
        Name = 'Elder Gifts'
        );
insert elderProd;

ID standardPBID = Test.getStandardPricebookId(); 

PricebookEntry standardPrice = new PricebookEntry(
        Pricebook2Id = pricebookId,
        Product2Id = prod.Id,
        UnitPrice = 10000,
        IsActive = true
        );
    insert standardPrice;

List<Pricebook2> standardPB = [select id from Pricebook2 where isStandard=true];
System.debug('Standard Pricebook found?');
System.debug(standardPB.size() > 0); // false

Pricebook2 customPB = new Pricebook2(
    Name='Custom Pricebook',
    isActive=true
    );
insert customPB;


PricebookEntry elderPBE = new PricebookEntry(
    Pricebook2Id = customPB.Id,
    Product2Id = elderProd.Id,
    UnitPrice = 0,
    IsActive = true
    );
insert elderPBE;

Error may be coming from following line:

UseStandardPrice = true