Testing Best Practices in Salesforce

1) If code uses conditional logic (including ternary operators), execute each branch.

2) Make calls to methods using both valid and invalid inputs.

3) Complete successfully without throwing any exceptions, unless those errors are expected and caught in       a try…catch block.

4)Always handle all exceptions that are caught, instead of merely catching the exceptions.

5) Use System.assert methods to prove that code behaves properly.

6)Use the runAs method to test your application in different user contexts.

7) Exercise bulk trigger functionality—use at least 20 records in your tests.

Testing and Code Coverage- The Apex testing framework generates code coverage numbers for your Apex classes and triggers every time you run one or more tests. Code coverage indicates how many executable lines of code in your classes and triggers have been exercised by test methods

Code Coverage Best Practices

1) Run tests to refresh code coverage numbers. Code coverage numbers aren't refreshed when updates     are made to Apex code in the organization unless tests are rerun.

2)If the organization has been updated since the last test run, the code coverage estimate can be incorrect. Rerun Apex tests to get a correct estimate.

3) The overall code coverage percentage in your organization doesn’t include code coverage from managed package tests. The only exception is when managed package tests cause your triggers to fire.



Why Code Coverage Numbers Differ Between Sandbox and Production 

 When Apex is deployed to production or uploaded as part of a package to the Salesforce AppExchange, Salesforce runs local tests in the destination organization. Sandbox and production environments often don’t contain the same data and metadata, so the code coverage results don’t always match. 

Test Failures -If the test results in one environment are different, the overall code coverage percentage doesn’t match. Before comparing code coverage numbers between sandbox and production,

Data Dependencies,Metadata Dependencies,Managed Package Tests,Deployment Resulting in Overall Coverage Lower Than 75%,Code Coverage in Production Dropping Below 75%

Recommended Process for Matching Code Coverage Numbers for Production - 

Use a Full Sandbox as the staging sandbox environment for production deployments.

To reduce dependencies on data in sandbox and production organizations, use test data in your Apex tests.

Reference - https://developer.salesforce.com