Best Practices while writing Test Classes ?
- Test Coverage Target Should not be limited to 75%”. It is not about coverage, It is about testing complete functionality
- If possible Don’t use seeAllData=true, Create your Own Test Data.
- Always use @testSetup method dedicated to create test records for that class. This is newly added annotation and very powerful. Any record created in this method will be available to all test methods of that class. Using @testSetup method will improve test execution performance by creating test records only once for that class. If you are not using this, means test record is created in each TestMethod which will be very slow.
- Create Different Class which will create Dummy Data for testing, and use it everywhere
- Use Test.startTest() to reset Governor limits in Test methods
- Use As much as Assertions like System.AssertEquals or System.AssertNotEquals
- If you are doing any Asynchronous operation in code, then don’t forget to call Test.stopTest() to make sure that operation is completed.
- Use System.runAs() method to enforce OWD and Profile related testings. This is very important from Security point of View.
- Always test Batch Capabilities of your code by passing 20 to 100 records.
- Use Test.isRunningTest() in your code to identify that context of class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code bock. It is very handy while testing for webservices, we can generate fake response easily.
- @TestVisible annotation can be used to access private members and methods inside Test Class. Now we don’t need to compromise with access specifiers for sake of code coverage.
- End your test class with “_Test”. So that in Apex Class list view, Main class and Test class will come together, resulting easy navigation and time saver.
- Always try to pass null values in every methods. This is the area where most of program fails, unknowingly.
No comments:
Post a Comment