[SalesForce] How to unit test a trigger when you don’t know the required fields

This is another issue addressed largely towards app developers.

Let's say I write an insert trigger. When I write the test case for it, what I would normally do is create a new object, insert it, and validate that whatever my trigger is supposed to do actually happened.

However, people add custom requirements to sobjects all the time. If they add 3 custom fields to the opportunity object and make them required, my test will now fail to insert because I'm missing those required fields.

Is it possible to create a test that can navigate around this issue?

Best Answer

Customers can have validation on custom fields via validation rules and triggers, so handling that in your unit tests without customer intervention is next to impossible. The first step to reducing issues is to have your test data populate all standard fields and ensure the data uses the most common formatting for your customer base (US style phone numbers and addresses for the US for example).

Beyond that you can use the new Reflection features added to Salesforce in Summer '12 to allow customers to create unit test data classes that can be used by your managed package. Basically you define a test data generation interface and the customer creates an Apex class to generate data for you. Here's an example of using Reflection in a similar manner on the DeveloperForce blog: http://blogs.developerforce.com/developer-relations/2012/05/dynamic-apex-class-instantiation-in-summer-12.html

Using the method for unit tests run on install might be problematic as you'd have to have the customer create the class before they install your package and your package could only look for the class by name (or iterate through all default namespace classes and check for the correct interface). However, it's no longer necessary for unit tests to run during installation for managed packages and by default they do not.

The Reflection method requires some coding knowledge on the customer side, but you could add a tool in your application to generate the custom unit test data class for the customer.

FYI, it's no longer necessary for managed package unit tests to succeed in customer orgs. They're not required on install, they will no longer prevent deployment to production and they don't count as part of the customers unit test coverage percentage for purposes of deployment. The only exception to that is if the customer uses ANT and sets the runAllTests parameter to true.

Related Topic