By: Urmila Pawar
Test Class Basics
Writing Unit Tests is an important part of the Salesforce Development Life Cycle. Before deploying the code developed into the production environment, Salesforce requires at least 75% of the code to be covered by our test classes. Salesforce has done this to make sure the code does not break in any Production situation. So it is our responsibility to verify every possible scenario using test methods.
Test Class Requires
- Building your own test data, as you will not have access to data within your organization until you mark your test class as (SeeAllData = true)
- Perform the intended tests only within Test.startTest(); and Test.stopTest();
- The most important step is to verify that your code has run successfully and given the intended output
Annotations Used in Test classes
- @isTest(SeeAllData=true) : Use this annotation to grant test classes and individual test methods access to all data in the organization
- @isTest(SeeAllData=false) : All test methods and classes by default have this behavior
- @isTest(isParallel=true) : Use this annotation to indicate test classes that can run in parallel
- @isTest(isParallel=false) : This annotation will indicate that test class that cannot run in parallel
- @testSetup : Methods defined with the @testSetup annotation are used for creating common test records that are available for all test methods in the class
Note: @isTest(SeeAllData=true) and @isTest(isParallel=true) annotations cannot be used together on the same Apex method.
Test Class for Trigger
Test Class for Controller
Test Class for Scheduler / Batch Class
Test Class For API Callouts
Test Classes do not allow API callouts. So we need to prepare an environment which will act similarly to API providers. All the calls will be made to this fake environment instead of the actual API provider.
- Be as descriptive as possible while giving names to the test methods
- methodName + ExpectedOutput + WhenGivenWhatData
- Make sure that you write a test method for every possible scenario. Do not worry about Apex Code limit as test methods and test classes are not counted as part of Apex code limits
- When we test every possible scenario, we don’t have to worry about Code Coverage, it will be as high as 100%. Salesforce requires a minimum 75% of code covered before the code can be deployed to production