This is something I've run into and worked around, but it still annoys me because I have to write test specific things in my non-test code (and can't get to 100% coverage because of it).

I can find no way to set the UnitPrice field in Test code. I've written a before insert trigger for OrderItem (aka Order Products in the UI now). When creating an OrderItem through the UI, the ListPrice field is filled in, with a copy of the Pricebooks Listprice. However, when I write my tests, there is no way to get the Unit price field to be anything other than null. I can't set it in the constructor (it's read-only) and even though I set a PricebookEntryId, the ListPrice is not filled in. This means I now have this code in my trigger:

Decimal theListPrice = 0;
if (theOrderItem.ListPrice != null)
    //ListPrice is set when adding from UI
    theListPrice = theOrderItem.ListPrice;
    //ListPrice is not set when adding from test code
    theListPrice = thePricebookentry.get(theOrderItem.PricebookentryID).UnitPrice;

(Actually, now that I think of it, I guess I could always do the 2nd thing.)

And this is my test code:

Account theTestAccount = new Account(Name='TestAccount');
insert theTestAccount;

Contact  theContact = new Contact(LastName='testContact', Email='noreply@test.com', 
    AccountId = theTestAccount.Id);
insert theContact;

//make a new order
Order theTestOrder = new Order(AccountId = theTestAccount.Id, PoNumber= 'Test', 
    EffectiveDate = Date.today(), BillToContactId = theContact.Id,
    Status='Draft', Pricebook2Id=Test.getStandardPricebookId() );
insert theTestOrder; 

//then add order items from pricebook
Product2 theProduct = new Product2(Name = 'test', Family = 'test');
insert theProduct;

PricebookEntry theStandardPrice = new PricebookEntry(
    Pricebook2Id = Test.getStandardPricebookId(), Product2Id = theProduct.Id,
UnitPrice = 1000, IsActive = true);
insert theStandardPrice;

OrderItem theTestOrderItem = new OrderItem(OrderId=theTestOrder.id,Quantity=1,
    PricebookEntryId=theSwitchStandardPrice.Id, UnitPrice=theSwitchStandardPrice.UnitPrice);
insert theTestOrderItem;

Is there any way to get the OrderItem ListPrice to be filled out under test? Or does everyone do workarounds similar to the one I have above?

  • Are there any failures in your test class? Also can you add insertion of theTestOrderItem field? – Raul Feb 17 '17 at 9:08
  • Hmm, my code got cut of it seems. There are no failures (but this is due to the extra 'theOrderItem.ListPrice != null' in the main class that I want to avoid). – Legolas Feb 17 '17 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.