[SalesForce] Writing tests for Managed Package

I'm developing a managed package and I need to implement some test classes to test my code. However, I'm not sure how to write my tests in such a way so that they don't break due to custom rules put in place by users where my package is going to be installed. Let's take this for example:

In my test class I need to prepare some test data in order to test my code. So I wrote this statement in order to arrange it:

insert new Account(Name = 'My Test Account');

However, this can easily break in a customer's org if a customer marked a random field as required on Account object.

Next, I thought about getting around this by mocking my classes and using a Dependency Injection approach to create records only in memory, so I don't have to worry if my test code will break some validation rule when inserting into a database. However, I then have a problem with related lists (i.e. child records), as they are read-only. The below statement will return an error that Contacts field is not writable:

Account acc = new Account(Name = 'My Test Account');
acc.Contacts = new Contact[]{new Contact(LastName = 'Doe')};

Does anybody have any ideas regarding how to get around these problems? Are there any best practices when writing test classes for packages?

Best Answer

Don't worry about coding defensively against your client's configuration; they're allowed to ignore certain types of test failures. This is noted in the documentation:

If a subscriber creates a validation rule, required field, or trigger on an object referenced by your package, your test might fail if it performs DML on this object. If this object is created only for testing purposes and never at runtime, and the creation fails due to these conflicts, you might be safe to ignore the error and continue the test. Otherwise, contact the customer and determine the impact.

The most important thing is that your code does not fail unit tests during upload, including code coverage. This is the only time you need to fix your code.

Related Topic