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?