Is it doable for Opportunity Product to be load using Test.loadData while Standard Price is not accessible in Test class?

I try to automate the data population make it easy for user to define scenario using in csv files (static resource) .I'm able to find answer how to map the relationship on Account,Opportunity,Contact in csv but I 'm not able to find solution for Opportunity Product.One of the reason is how we going to define Price book Entry in Test Class for this case ?

1 Answer 1


Use Test.getStandardPricebookId() to get StandardPriceBookId in Test Class.

//create Account
Account acct = new Account(Name='test',......);
insert acct;

Opportunity oppty = new Opportunity(Name='TestOppty', AccountId=acct.Id,....);
insert oppty;

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

ID standardPBID = Test.getStandardPricebookId(); 

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

List<Pricebook2> standardPB = [select id from Pricebook2 where isStandard=true];

OpportunityLineItem oli = new OpportunityLineItem(
    OpportunityId = oppty.Id,
    Quantity = 5,
    PricebookEntryId = standardPrice.Id,
    UnitPrice = 1);
insert oli;

//following code for Custom pricebook

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

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


You have to use actual id of Standard Pricebook as you can't insert a standard pricebook via testmethods. Refer this Test.loadData() - undocumented (but useful) behavior loading relationships

  • I am looking a way to populate Opportunity Product data from Test.loadData (Static Resource-csv ) not code it in apex class. Is it possible?My bad, maybe my question is not clear enough. Updated it.
    – unidha
    Jul 15, 2017 at 6:24
  • updated my answer Jul 15, 2017 at 6:36
  • This issue will it solve if I just @seealldata=true ?
    – unidha
    Jul 15, 2017 at 7:46
  • 1
    @unidha - avoid seeAllData like the plague for this use case. Std pricebookId is the same across sandboxes and PROD so Santanu's suggestion at bottom of answer is the way to go using Test.LoadData
    – cropredy
    Jul 16, 2017 at 23:03

You must log in to answer this question.

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