Testing Best Practices

Good tests do the following:
Note

Note

To protect the privacy of your data, make sure that test error messages and exception details don’t contain any personal data. The Apex exception handler and testing framework can’t determine if sensitive data is contained in user-defined messages and details. To include personal data in custom Apex exceptions, we recommend that you create an Exception subclass with new properties that hold the personal data. Then, don’t include subclass property information in the exception's message string.

If you are running many tests, test the classes in your organization individually in the Salesforce user interface instead of using the Run All Tests button to run them all together.

Best Practices for Parallel Test Execution

Tests that are started from the Salesforce user interface (including the Developer Console) run in parallel. Parallel test execution can speed up test run time. Sometimes, parallel test execution results in data contention issues, and you can turn off parallel execution in those cases. In particular, data contention issues and UNABLE_TO_LOCK_ROW errors can occur in the following cases:
  • When tests update the same records at the same time. Updating the same records typically occurs when tests don’t create their own data and turn off data isolation to access the organization’s data.
  • When a deadlock occurs in tests that are running in parallel and that try to create records with duplicate index field values. A deadlock occurs when two running tests are waiting for each other to roll back data. Such a wait can happen if two tests insert records with the same unique index field values in different orders.
You can prevent receiving those errors by turning off parallel test execution in the Salesforce user interface:
  1. From Setup, enter Apex Test.
  2. Click Options....
  3. In the Apex Test Execution Options dialog, select Disable Parallel Apex Testing and then click OK.

Test classes annotated with IsTest(isParallel=true) indicate that the test class can run concurrently with more than the default number of concurrent test classes. This annotation overrides default settings.