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

Test method for Trigger

I wrote a trigger on OpportunityProductLineItem and now I am trying to write a test for it.  My understanding is that I need to instanciate an OpportunityProductLineItem that will set off the trigger.  My confusion comes when I try to make ... 


OpportunityProductLineItem opi = new OpportunityProductLineItem();


I get errors saying I do not have the required field OpportunityId.  How/Where am I supposed to get an OpporutnityID from?


Opportunity opp = new Opportunity(name = 'a name', put required fields here just like name and give some values);

insert opp;


Now query for above inserted opp which will give you opportunity id.


Marked in green color : am not sure of the syntax, sorry.


Is this really the right way to do this?  It seems like im needing to go down a pretty deep hole. Every object I try to create is dependent on 2 other objects below it and I am continually getting : MISSING_REQUIRED_FIELD


current code


Opportunity opp = new Opportunity(name = 'testName', stageName = 'Prospecting', CloseDate =;
insert opp;
OpportunityLineItem opi = new OpportunityLineItem();
opi.OpportunityId =;
opi.quantity = 1;
opi.totalPrice = 10;
Pricebookentry pbe = new Pricebookentry(UnitPrice = 1);
insert pbe;
opi.pricebookentryid =;
insert opi;


MISSING REQUIRED FIELDS [pricebook2ID, product2ID]


If I create a pricebook2 and a product2 they will probably need me to create 4 more missing fields and so on and so on...


Is this really the right way to test a trigger on OpportunityProductLineItem?


why does he even need to query?


he can directly assign the Opportunity Id without querying.


Opportunity opp = new Opportunity(Name='Test', ALL OTHER REQUIRED FIELDS ON OPPORTUNITY);

insert opp;



OpportunityProductLineItem opi = new OpportunityProductLineItem();

opi.OpportunityId = opp.Id;

*other required fields, if any.


that should do it for you!



*Note : Whenever you need some data, like here you needed the opportunity Id, always make a point for creating all the data you need in your test class, the reason being while you deploy/port that class to some other Org, there may be no data there which can affect your test coverage. So here we created an Opportunity, inserted it and then assigned it's id to the Opportunity Product Line Item record.


My problem is the *other required fields, if any* is actually a lot of fields on alot of different objects.  But I guess I do understand that there is no way to guarentee that there is data in the database that already matches the trigger criteria.


yes, in that case you need to create test data for all those objects and then refer them in your Opportunity Line Item object. That's the ideal way to make sure your test coverage never fails irrespective of data in the Org.