Learn 3 Salesforce testing best practices from my Salesforce MVP unit tests for Contacts:
Unit tests are a readable specification: test names include a specific action and expected result. Methods are short and descriptive, so you can understand the overall flow before diving into the details. Methods are also reusable across tests, so you have less code to read and maintain.
Isolated Test Data
Isolated test data is an important Salesforce testing best practice. Your tests will run in various sandbox and production environments, so they should create their own data. Build large test data sets before calling startTest so your test still has full execution limits. By default, Salesforce runs your tests isolated from real production data. When you do need a Profile or other system data, always query to get the right one for that environment.
Unit tests provide more than Salesforce’s mandatory 75% code coverage. As a Salesforce testing best practice, they should assert a specific result. Call stopTest before your assertions to force any asynchronous code to finish. Since other code might change data, run a fresh query for final results. Assert your expected results with clear error messages that are easy to understand.
Salesforce Testing Best Practices
My standard Salesforce unit tests for Contacts introduced 3 Salesforce testing best practices: Readability, Isolated Test Data, and Clear Assertions. Use these best practices in your own Salesforce unit tests to deliver self-documenting and deployable tests that explain your clever code to future developers.
How will you apply these Salesforce testing best practices?