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
Som_11Som_11 

What is the best practice to write test classes where we need to add product

What is the best practice to write test classes where we need to add product for OrderItem. Should we create an New product as part of test data as we are creating account.
Abhishek BansalAbhishek Bansal
Hi Somesh,

Yes you need to craete the products in test class. Sample code is below:
// Insert Product
    Product2 p = new Product2();
    p.Name = ' Test Product ';
    p.Description='Test Product Entry 1';
    p.productCode = 'ABC';
    p.isActive = true;
    insert p;
    

    Id pricebookId = Test.getStandardPricebookId();
    
    // Insert PricebookEntry

    PricebookEntry standardPrice = new PricebookEntry();
    standardPrice.Pricebook2Id = pricebookId;
    standardPrice.Product2Id = p.Id;
    standardPrice.UnitPrice = 1;
    standardPrice.IsActive = true;
    standardPrice.UseStandardPrice = false;
    insert standardPrice ;
    
    // Insert Order
    
    Order o = new Order();
    o.Name = 'Test Order ';
    o.Status = 'Draft';
    o.EffectiveDate = system.today();
    o.EndDate = system.today() + 4;
    o.AccountId = a.id;
    o.Pricebook2Id =  pricebookId ;
    
    insert o;
    
    // Insert Order Item

    OrderItem i = new OrderItem();
    i.OrderId = o.id;
    i.Quantity = 24;
    i.UnitPrice = 240;
    i.Product2id = p.id;
    i.PricebookEntryId=standardPrice.id;
    insert i;

Let me know if you need more help

Thanks,
Abhishek Bansla.
vishal-negandhivishal-negandhi

Hi Somesh, 

Except a few setup objects, no data is available in test classes by default. 

So as a thumb rule, you MUST create test data for all objects that you need for your logic to run. 

It's well explained here - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_data.htm

Hope this helps.

Best,

Vishal