[SalesForce] OpportunityLineItem in test classes

I am trying to insert OpportunityLineItem record in my test class but unable to insert.

Account acc = new Account(Name = 'Test');
insert acc;

Opportunity oppObj = new Opportunity(Name = 'TestOpp',AccountID = acc.Id,Amount = 2000,CloseDate=Date.today(),StageName='Close Won',Type='New Customer');
insert oppObj;

Product2 newProd = new Product2(Name = 'test product', family = 'test family');
insert newProd;

PriceBookEntry pbEntry = new PriceBookEntry(
    UnitPrice = 300,
    PriceBook2Id = [select id from PriceBook2 where isStandard = true].Id,
    Product2Id = newProd.Id,
    IsActive = true);

insert pbEntry ;

OpportunityLineItem oppLine = new OpportunityLineItem(pricebookentryid=pbEntry.Id,TotalPrice=2000,Quantity = 2,OpportunityID = oppObj.Id);
insert oppLine;

[select id from PriceBook2 where isStandard = true] is not returning any data.

any idea how to insert OpportunityLineItem.

Thanks

Best Answer

Instead of of this:

Pricebook = [select id from PriceBook2 where isStandard = true].Id

Why not try this instead?

PriceBook2Id = Test.getStandardPricebookId()
Related Topic