function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mel LisauMel Lisau 

How can i create a unit test for OrderItem ?

I am trying to create a test for "after insert" on OrderItem.,
I have so far the following:


@isTest 
 public static testMethod void MyTestOrderItem()   { 
   List<Account> AccountList = new List<Account>();
   Account Account_0 = new Account( Name='NAME1');
   AccountList.add(Account_0);
   Account Account_1 = new Account( Name='NAME2');
   AccountList.add(Account_1);
   insert AccountList;


    Product2 p = new Product2();
    p.Name = ' Test Product ';
    p.Description='Test Product Entry 2';
    p.productCode = 'ABCD';
    p.isActive = true;
    insert p;


   PriceBook2 pb2Standard = [select Id from Pricebook2 where isStandard=true];
   Id pricebookId = pb2Standard.Id;

    // Insert PricebookEntry=
    PricebookEntry standardPrice = new PricebookEntry();
    standardPrice.Pricebook2Id = pricebookId;
    standardPrice.Product2Id = p.Id;
    standardPrice.UnitPrice = 1;
    standardPrice.IsActive = true;
    standardPrice.UseStandardPrice = false;
    insert standardPrice;


  List<Order> OrderList = new List<Order>();
  Order Order_0 = new Order(Pricebook2Id= pricebookId,  Status='Draft',Name='4TJI5',EffectiveDate=Date.Today(),AccountId=AccountList[0].Id);
  OrderList.add(Order_0);
  Order Order_1 = new Order(Pricebook2Id= pricebookId, Status='Draft',Name='0TXZU',EffectiveDate=Date.Today(),AccountId=AccountList[0].Id);
  OrderList.add(Order_1);
  insert OrderList;
 
  List<OrderItem> OrderItemList = new List<OrderItem>();
  OrderItem OrderItem_0 = new OrderItem(Product2id = p.id , PriceBookEntryId=standardPrice.Id, Description='FD3G8',OrderId=OrderList[0].Id);
  OrderItemList.add(OrderItem_0);
  OrderItem OrderItem_1 = new OrderItem( Product2id = p.id, PricebookEntryId=standardPrice.Id, Description='PB4DM',OrderId=OrderList[0].Id);
  OrderItemList.add(OrderItem_1);
  insert OrderItemList;

}

Would this help in my unit test , or is there a simpler test for OrderItem ?
SwethaSwetha (Salesforce Developers) 
HI Mel Lisau,
The code looks good to me. Are you seeing any error message or having coverage issues?

In general, you must first make sure that the Order on which you are operating has a Pricebook associated with it before you can add any Products to it as OrderItems.
The article https://salesforce.stackexchange.com/questions/49472/problem-with-inserting-a-new-order-item gives a good insight on orderitem

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you