Apex Test Class Best Practices in Salesforce?
2 min readNov 4, 2020
There are many points keep in mind whenever we write test class:-
- Use @isTest at the Top for all the test classes.
- Avoid Using Hard Coding Ids anywhere in test Class
- Use System.runAs() method to test the functionality in user Context
- Check debug log. Make sure right tick must appear when you run your test class. Else check for errors.
- Use Test.startTest() and Test.stopTest() statement to increase Governor Limits of your test code.
- Use System.assertEquals() to see if your code has the expected outcomes
- Test in bulk: Test to see if your code can run on 200 records at once. This is the maximum number of records that can be evaluated in a single trigger by Salesforce.
- To deploy to production at-least 75% code coverage is required. and also the main functionality has been covered. If possible increase code coverage up to 95%.
- We should not focus on the percentage of code coverage, we should make sure that every use case should covered including positive, negative,bulk and single record.
- Test method should static and no void return type.
- @Testvisible annotation to make visible private methods inside test classes.
- Test method cannot be used to test web-service call out . Please use call out mock .
- You can’t send email from test method.
- Use the @testSetup method to insert the common test data into the Test class that will flow all over the test class.
- Do not put (seeAllData = true) in test class otherwise, use it for exceptional cases.
Originally published at https://www.lifedreamguide.com.