Thursday, November 17, 2011

Revolutionizing Unit Tests in Salesforce with Public Test Classes

One of the coolest features in Winter '12 for any organization that uses Apex has to be public test classes.

Why? One main reason: Public test classes combined with a tool like HardBoil will revolutionize unit testing in Salesforce!

Imagine a world where functional users (yes, functional users!), not developers, actually setup all of the unit tests through an interactive process that...
  • Saves developers countless hours of writing boilerplate code.
  • Drastically reduces human error in staging test data, checking pre-conditions and asserting post-conditions.
  • Produces clean, self-documenting and easy-to-read test code.
  • And trains functional users to learn the data structures and respect data quality, all at the same time!

Here's the immediately achievable concept: Create a single, public test class (perhaps using HardBoil) called something like EnterpriseTestDb. Then, all one has to do is start every test method by instantiating EnterpriseTestDb as follows:
// Stage test data.

EnterpriseTestDb db = new EnterpriseTestDb();

// Set test parameters.

Account largeAccount =
        db.getAccountByName('Acme Corporation');

Contact mainContact =
        db.getContactByName('John Doe');

...

The best parts about all of this, again, is that...
  • Not a single second of developer time was needed to create potentially hundreds of test records that can support every single unit test in the entire org!
  • Functional users learned the data structure by setting up all of the test data for their developers!

And the long-term concept? Automatically generating test methods already setup to check pre-conditions and assert post-conditions, thereby allowing developers to simply fill in the code in each test method to move from the pre-condition to the post-condition.

In short, I can't wait for this new world to arrive.