Friday, October 4, 2013

Force.com #Tested, Standard Pattern for Apex Unit Tests

The first step to writing an Apex unit test is... just to lay down the framework. The boring stuff, really. Declare the class, add the isTest annotation, declare a testMethod-qualified method, etc. And to make boring matters worse, in practice Apex unit testing is pretty important to get right.

The reason is simple: In addition to deploying your own customizations, Salesforce will upgrade your org 3 times a year with 100+ new features per release. Whether you like it or not. Assuming CRM is fairly important to your organization, who's going to run tests for your org every time a new release happens, to make sure the business can continue to operate?

  • Code coverage and test methods are intended to make sure that customizations work correctly, release after release, with minimal human effort
  • Good tests help to make sure your code works not only for one-off record edits but also for batch inserts, updates and deletes
  • With good intent, Salesforce requires you to have at least 75% code coverage to deploy new code. So, if you have to write tests anyway, let's just do it right the first time. Build the tests to add value as regression tests, instead of just time drains.


Understanding the significance of these tests, a new developer may find writing good tests to be quite daunting, second-guessing himself and worrying about whether he followed best practices. Then, in frustration, he could decide to just "screw it" and hack something out to achieve the minimum amount of code coverage required to just push a risky feature into production. Bad outcome.

To help a developer avoid this sub-optimal decision, he can adopt a standard test class structure that is easily adapted for all Apex unit tests. Below is one such self-documenting template for Apex unit tests, using a contrived example of trying to roll-up all activities related to a particular contact record.


There are lots of comments and little code in the above block, which is intentional to leave material for the rest of this series. :-) Subsequent posts will dive into each step above in more detail, walking through sample implementations by building out this example trigger test class.

But regardless of whether you're testing triggers, controllers, extensions, Schedulables or anything else in Apex, the general steps above should remain the same for your test methods. This way, Apex unit tests transform from time-and-materials liabilities in a Salesforce org to valuable assets that shine every time anyone goes to release a new feature.