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 ?

up vote 1 down vote accepted

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',
    isActive=true
    );
insert customPB;


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

Update

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 '17 at 6:24
  • updated my answer – Santanu Boral Jul 15 '17 at 6:36
  • This issue will it solve if I just @seealldata=true ? – unidha Jul 15 '17 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 '17 at 23:03

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.