I've got a managed package that includes an after insert/update trigger on Opportunity. The trigger dynamically creates records that are related to the Opportunity. Hence being after triggers so the Opportunities Id can be used.
I recently ran into problems with the trigger where I had assumed there couldn't be one of these related records (that only I create) in the after insert trigger.
This assumption turned out to be wrong when a subscriber org created an After Insert trigger on Opportunity that inserted OpportunityLineItem records. This caused the the following sequence of events:
- Opportunity is inserted
- Subscriber after insert trigger code inserts OpportunityLineItems for the Opportunity
- Managed package Opportunity After Update trigger fires and inserts records related to the Opportunity
- Managed package Opportunity After Insert trigger fires and attempts to insert records without checking for existing records
- The insertion of the related records fails as they were already created by the Opportunity After Update trigger that occured when the OpportunityLineItems were inserted.
This was further complicated by needing to support additional changes that might be made to the Opportunity fields by Workflow rules. Otherwise some basic trigger recursion protection would have prevented the problem.
This brings me back to my question. I know why it is happening, but how do I create this as a test case in the packaging org?
As far as I can tell I'd need to have an additional trigger that fires before the existing one and inserts OpportunityLineItem records. That's tricky for two reasons:
- I couldn't be sure that an additional trigger in the packaging org would always fire before the existing trigger
- I wouldn't want the testing only trigger to become part of the managed package as it serves no other purpose. Maybe I leave it out and then either let the corresponding test case fail in the subscriber org (which is fine) or short circuit it so it passes if the test trigger isn't present.