[SalesForce] Process Builder causing Apex Test class failures – How to handle

Hoping someone can help with the following issue I am currently experiencing.

I have created a new process via the process builder that sets the Contact owner to be the same as the Account Owner on creation of the Contact. 

Now, when I 'run all tests' during deployment or in Eclipse IDE I run into test failures. The affected classes all point to lines in the code wherever a Contact needs to be created in the test class.

Is there anything I can introduce into the test classes to prevent them from failing? or is there something I can introduce to the code to prevent the process from firing when a Contact is being created for code coverage?

To ensure successful deployments I have to deactivate this process and reactivate afterwards.. just so it will upload to Production. Less than ideal.  I also created this process to replace an old Apex trigger that did the same job but very unreliably. Now I'm starting to regret archiving this trigger given the interference the process is having on the existing test classes in our Salesforce org. 

Any advice/tips/experiences to share on resolving this kind of issue would be greatly appreciated!

Also going to include an error message and the lines of code throwing this error below.

error message:

'System.DmlException: Insert failed. First exception on row 0; first
error: UNKNOWN_EXCEPTION, We can't save this record because the “Set
Contact Owner to Org Owner on Creation” process failed. Give your
Salesforce admin these details. An unhandled fault has occurred in
this flow

An unhandled fault has occurred while processing the
flow. Please contact your system administrator for more information.:
[]'

Class.MyProfilePageControllerTest.testSave: line 35, column 1

line 32 to 35, column 1:

  Contact c = new Contact();
            c.LastName = 'TestContact';
            c.mailingcountry = 'Ireland';
            insert c;

Thanks!

Best Answer

There are four approaches to avoiding this issue

  1. Update the testmethods to include the necessary data that the PBs require (Phil W's suggestion)
  2. Update the PBs to do a better job of testing for the absence of related objects so they don't blow up
  3. Gate the PBs with a custom setting that you enable in your testmethods to turn off the PBs for those testmethods where you are having this issue
  4. Rework your testmethods and code to use dependency injection and mocking. This is well covered in Force.com Enterprise Architecture 2nd Edition by Andrew Fawcett, now VP at SFDC. This approach means you can avoid doing DML in your testmethods and hence the PBs won't execute. It is great for unit testing.

In our org, we use a combination of 1 (some), 2 (definitely) and 4 (most definitely)

Related Topic