Mobile Development Manager
Innovative Force.com and Mobile Architect, creator of 2nd Opinion iPhone app, and author of open source Force.com Toolkit for Google Analytics. Avid photographer, snowboarder, and mountain biker.
Using the right data in your Force.com tests can be tricky, but this post will take you through a quick evolution and share our best practices for test data.<br><br>Let's start by simply grabbing some existing data for our test:<br><pre class="brush:apex">
Contact c = [select Id from Contact where Id = '123'];
</pre> <br>When that blows up in a different org, we make it a little more flexible:<br><pre class="brush:apex">
Contact c = [select Id from Contact limit 1];
</pre> <br>That works until we deploy to an empty org, like a configuration-only sandbox. At this point, we realize we should really be creating unique test data from scratch. Since test contexts always rollback all data, we can do this freely without worrying about polluting any real data in production:<br><pre class="brush:apex">
Contact c = new Contact(LastName = 'Botos');
</pre><br>Now our test data works in any org! We just had to remember what fields were required on Contact, and could add additional fields that might be used in our test.<br><br>In the real world, though, we're often jumping into new orgs with unknown required fields and relationships. What if our org's Contact required a lookup to a custom object Client__c, which it turn required field Industry__c? After a bit of digging and trial and error, we come up with:<br><pre class="brush:apex">
Client__c client = new Client__c(Industry__c = 'Life Sciences');
Contact c = new Contact(LastName = 'Botos', Client__c = client.Id);
</pre><br>Whew - that's going to be a real pain as we get into complex orgs! I had the same thought, and tackled the problem during our May 2011 Mavens Hackathon with <a target="_blank" href="https://github.com/mbotos/SmartFactory-for-Force.com">SmartFactory</a>. SmartFactory is a native Force.com library that uses Salesforce's own metadata describe methods to understand the structure of your objects and automatically create test data:<br><pre class="brush:apex">
Contact c = (Contact)SmartFactory.createSObject('Contact', true);</pre>
</pre><br>The second argument toggles the cascade option, which populates any lookup fields on the object with their own newly created objects. It's a powerful way to create hierarchies of test data quickly and easily so you can focus on writing test and implementation logic.<br><br><a target="_blank" href="https://github.com/mbotos/SmartFactory-for-Force.com">SmartFactory</a> is part of the open source collection Mavens has released on GitHub; you're free to use it in your projects and contribute any additions you find useful.<br><br>This is by no means the last chapter in the evolution of test data; I look forward to hearing your own thoughts and best practices below!