Tuesday, 15 July 2014

Best Practices of Test Classes in Apex


  • Use Test.startTest() to reset Governor limits in Test methods
  • If you are doing any Asynchronous operation in code, then don’t forget to callTest.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.
How to write Test method of Controller Extension for StandardController ?
Example :
//Lets Assume we are writing Controller Extension for Account
Account acct = [SELECT ID FROM Account LIMIT 1];

//Start Test Context, It will reset all Governor limits
Test.startTest();

//Inform Test Class to set current page as your Page where Extension is used
Test.setCurrentPage(Page.YOUR_PAGE);

//Instantiate object of "ApexPages.StandardController" by passing object
ApexPages.StandardController stdController = new ApexPages.StandardController(acct);

//Now, create Object of your Controller extension by passing object of standardController
YOUR_Extension ext = new YOUR_Extension(stdController);

//Here you can test all public methods defined on Extension "ext"
//..... your code

//Finish Test
Test.stopTest();