2

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

2 Answers 2

4

Instead of of this:

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

Why not try this instead?

PriceBook2Id = Test.getStandardPricebookId()
2
  • Thanks a lot @Programmable Medley, your suggestion worked !!
    – San
    Apr 16, 2015 at 21:08
  • Glad I can help. Please make sure to mark that you excepted the answer. Apr 16, 2015 at 21:09
1

The reason it is not working in your test class is because to run SOQL query on data in org use need to annotate the Test class with SeeAllData=true. Else you can use Test.getStandardPricebookId(); to get ID of the standard price book in your organization regardless of whether the test can query organization data (irrespective of the state of SeeAllData).

3
  • 2
    Please note: You should avoid using the SeeAllData=true as much as possible. There are numerous issues with it and should only be used as a last resort - which is very, very rare. Apr 16, 2015 at 20:54
  • Thanks @nevrekar_amey for your suggestion and quick reply i appreciate. When i am using SeeAllData=true then getting duplicate record error on second run for few records so using Test.getStandardPricebookId() approch.
    – San
    Apr 16, 2015 at 21:09
  • I concur with @programmable Medley suggestion regarding SeeAllData = true , to be avoided as much as possible. Apr 16, 2015 at 21:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .