September 3, 2011

More Apex Testing with SmartFactory !

Creating Mock objects for Apex test cases is a pain, SmartFactory from Matthew Botos is a great API that really simplifies this task. One can create standard and custom object with some sensible defaults for all fields with just one line of code, shown below
// create standard Account object
Account account = (Account)SmartFactory.createSObject('Account');
// Create a custom object
Custom_Object__c customObject = (Custom_Object__c)SmartFactory.createSObject('Custom_Object__c');

My journey with SmartFactory … !

We started using and liking SmartFactory internally on some of our projects. I was getting continuous feedback from my team about goods and gaps of this API. This attracted me towards this API, I became very much interested in this project and started contributing to fix those gaps for our self and community.
The first item fixed was “Field Describe limit reached with SmartFactory.”. Here caching support was added to save describe calls, on creating multiple instances of same object.
Moving next the items on list were following
I am glad to share with you all that, finally all these items are fixed and pull request is raised for merge into the main repos.
Most important of the above mentioned issues/items was Issue#6. Now apart from the ways described in code snippets above, one can also create mock Sobjects initialized with default values, as shown below
Map<String, Object> accValues = 
                   new Map<String, Object> { 'AnnualRevenue' => 20000.00,
                                        'Description' => 'My Account Description', 
                                        'Phone' => '123-234-2233' };
Account acc = (Account)SmartFactory.createSObject('Account', accValues); 
In the end, I would like to say that Matthew was really cooperative and open in adapting/discussing the changes, this is really appreciable to keep up the open source contribution spirit high !