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

Testcode challenge for new Opportunity with OpportunityContactRole

We have a process wherein new opportunities are initiated from a contact screen as a result of a relationship with a campaign.  We have an opportunity trigger, set for after insert, that will look to the OpportunityContactRole to pickup the id of the contact that initiated the opportunity (this is specific to opportunities opened from within a contact's related opportunity list), pickup the campaignid from the opportunity that was created, and will then lookup in the campaignmember object to update the status as responded if the contact is found in the campaignmember list, and if the contact isn't found it will insert the contact as a member of the campaign and set the status to responded.  The Apex trigger works and performs as expected.


The test code however is a challenge as we can:

create an account

create a contact

create a campaign


We now are ready to create the Opportunity - but the issue is we can't create an OpportunityContactRole and insert it before the Opportunity is created (no opportunity id exists at that point), hence the test code won't cover the code sections that do the work of looking up the contactid from the OpportunityContactRole.


When performed through interactive UI, SFDC is somehow inserting the OpportunityContactRole so that it is available to the trigger when the  "after insert" of the Opportunity occurs.  Not certain how I can create the same conditions for test code coverage purposes.  Looking for some ideas that will help resolve this.


I am having the same issue, if you found a solution please do tell.  I will post up if I find one as well.