I tried looking up but could not find. Is there a way to simulate creating an opportunity from a contact record in a test class (like how we do via the GUI). As you know, this will cause SF to create an Opportunity Contact Role(OCR) by default (before the after-insert trigger on opportunity). If I do create an opp in the test class, it's not creating the OCR and hence that piece of code is not covered under my test class and I'm trying to see if I could cover that too.

Any pointers would be welcome

  • Why don't you just create a separate OCR and link it to your previously created objects? – Marc Zaharescu Apr 1 '16 at 8:21
  • I could certainly do that, but I was wondering if there's a way to simulate the standard out of the box behavior in a test class. What's really the 'correct' way of doing this? – JJSHHS Apr 1 '16 at 13:39
  • The SFDC UI executes multiple DMLs for this use case; testmethods and apex have to do things 1x1 (explicitly). – cropredy Apr 1 '16 at 23:35

Not every org has OCR's enabled, so while "it" may create one in your org by default, "it" doesn't do that in every org. You may not realize it, but your org may be doing this using a trigger, workflow, or some other solution.

Just like you need to create a contact with an account, and later the opportunity, you'll also need to create the Opportunity Contact Role record as well for your test class if you want to cover that portion of your code. That's the way it is with test classes. You're expected to create all of your data which includes hooking up these kinds of relationships.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.