Hey, buddy good to see you! By the end of this one, you will be able to answer some of the questions on the basis of your understanding, questions such as what is the importance of testing and the best practice to do so...
Since we meet here then you must know about the apex class that you have created or worked on then there is the requirement of the deployment to it on the production org for this one must know that it’s a standard requirement created by Salesforce for quality production. Here for this purpose, we create test classes to check the quality of that class and make it fit for the deployment.
Don't forget to check out: Apex Basics and Database | Salesforce Apex Tutorial Guide
Now, let’s discuss best practices to remember while writing...
- Try to cover as many lines of code as possible. Before you can deploy Apex or package it for the Salesforce AppExchange, the following must be true.
- If the code uses conditional logic (including ternary operators), execute each branch.
- Calls methods using both valid and invalid inputs.
- Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try, catch block.
- Always handle all exceptions that are possible.
- Use system.assert methods to prove code behaviour.
- Use the runAs method to test your application in different user contexts.
- Exercise bulk trigger functionality, and process at least 20 records in your tests.
- Use the ORDER BY keywords to ensure that records are returned in the expected order.
- Don’t assume recordIds the sequential.
- Set up test data.
- Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
- Create all test data before calling the Test.startTest method.
- Since tests don't commit, you don't have to delete any data.
- Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on.
- Test classes individually, don’t rely on a single test.
Check out another amazing blog by Akash here: Create Sharing Rules Unit in Salesforce - Learn Here
Points to Remember
- Record IDs are not created in ascending order unless you insert multiple records with the same request. For example, if you create account A, and receive the ID 001D000000IEEmT, then create account B, the ID of account B may, or may not be sequentially higher.
- Test class must cover 75% with fully successful tests.
- The trigger must have some test coverage.
- All triggers and classes must compile successfully.
- System.debug is not considered part of the coverage.
- When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
- Try to cover more than 75% coverage to increase efficiency and decrease the chance of error while deployment.