[SalesForce] Apex Trigger test Class Issue; No Standard Price Defined

Here is my Apex Trigger

trigger ProductNameTrigger on QuoteLineItem (before insert) {
    list<QuoteLineItem> plist = new list<QuoteLineItem>();
    for(quotelineitem q : [select id, Product2.name, product2id, Product2_Name__c from QuoteLineItem where id =:trigger.new]){
        q.Product2_Name__c = q.Product2.name;
        plist.add(q);
    }
    update plist;
}

and here is my test class

private static testMethod void testTrig(){
    Opportunity o = new Opportunity(name='testOp', StageName='Closed', CloseDate=date.today());
    insert o;
    Product2 prodTest = new Product2(Name = 'testProduct', StandardPrice=20);
    insert prodTest;
    Quote quoteTest = new Quote(OpportunityId = o.id);
    quoteTest.name = 'testQuote';
    insert quoteTest;
    PriceBook2 pbook = new PriceBook2(name='testBook');
    insert pbook;
    PriceBookEntry entry = new PriceBookEntry( Product2Id=prodTese.id, UnitPrice=0, PriceBook2Id=pbook.id, UseStandardPrice=true);
    insert entry;

    QuoteLineItem q = new QuoteLineItem(Product2Id = prodTest.id, PriceBookEntryId=entry.id, Quantity=0, UnitPrice=entry.UnitPrice);
    insert q;

    System.assertEquals(prodTest.name, q.Product2_Name__c);
}

and I am getting an Error that states

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

Any Idea how to fix this?

Best Answer

The reason for this error is that when using custom pricebooks (pBook), before you can add a PBE (PricebookEntry) for that product | pricebook combination, you must first insert a PBE for the same product | standard Pricebook combination

The standard pricebook's id can be found from Test.getStandardPricebookId(). You do not create a standard pricebook in the testmethod

You'll need something like:

PriceBookEntry[] entryList = new List<PriceBookEntry> {
    new PricebookEntry( Product2Id=prodTese.id, UnitPrice=0,
                        PriceBook2Id=Test.getStandardPricebookId(), // **
                        UseStandardPrice=false,isActive=true),
    new PricebookEntry( Product2Id=prodTese.id, UnitPrice=0, 
                        PriceBook2Id=pbook.id, 
                        UseStandardPrice=true,isActive=true)
    };
insert entryList;
Related Topic