Wednesday, December 23, 2015

Best Practices for Test Classes in salesforce?

  1. Very important and first, “Test Coverage Target Should not be limited to 75%”. It is not about coverage, It is about testing complete functionality. It will be always better if your code fails during testing, It will be less devastating than failing functionality after product release.
  2. If possible Don’t use seeAllData=true, Create your Own Test Data.
  3. Create Different Class which will create Dummy Data for testing, and use it everywhere (You have to be very careful, as sometimes it may slow down test class execution by creating unnecessary data which does not require by every test methods. So few developer prefer test data creation per Test class)
  4. If your Object’s Schema is not changing frequently, you can create CSV file of records and load in static resource. This file will act as Test data for your Test Classes.
  5. Use As much as Assertions like System.AssertEquals or System.AssertNotEquals
  6. Use Test.startTest() to reset Governor limits in Test methods
  7. If you are doing any Asynchronous operation in code, then don’t forget to call Test.stopTest() to make sure that operation is completed.
  8. Use System.runAs() method to enforce OWD and Profile related testings. This is very important from Security point of View.
  9. Always try to pass null values in every methods. This is the area where most of program fails, unknowingly.
  10. Always test Batch Capabilities of your code by passing 20 to 100 records.
  11. 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.
  12. @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.

No comments:

Post a Comment