Thursday, November 8, 2018

Best Practices for writing Apex Test Class in Salesforce.com

Best Practices for writing Apex Test Class

1) Use @isTest keyword to declare apex test class and methods.

2) Use @testSetup to set up test data required for testing.

3) Use @TestVisible in apex controller method defined as private, so it can be accessed in test class.

4) Use System.runAs(user) to test apex on profile level.

5) Avoid using SeeAllData = true because it allows test methods to access database records for testing, resulting it can fail in production where database not having corresponding records.

Note: Only use SeeAllData = true, if there are sObjects that doesn't allow DML operation. e.g. PriceBook creation.

6) Use Test.startTest and Test.stopTest to reset the governor limit, and also to forces the asynchronous methods to execute synchronously, so that the results can be asserted.

7) Use System.assertEquals(expected, actual, msg) and System.assertNotEquals(expected, actual, msg) to assert expected and actual values from test methods.

8) Avoid Hard Code Ids of any sObject in any test method.

9) Use Null Pointer Exception test as part of negative testing for each method, specially the methods which takes parameters.


Test class important keywords are 
  • @isTest
  • @testSetup
  • @TestVisible
  • System.runAs(user)
  • SeeAllData = true
  • Test.startTest and Test.stopTest
  • System.assert(condition, msg)
  • System.assertEquals(expected, actual, msg)
  • System.assertNotEquals(expected, actual, msg)









No comments:

Post a Comment

Validation in flow input text field in sfdc: Maximum 255 characters limit

The input text field validate in sfdc flow behaves opposite of the generic sfdc validation rule.  Here the validation formula is evaluating ...