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

  1. 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)
  2. Perform the intended tests only within Test.startTest(); and Test.stopTest();
  3. The most important step is to verify that your code has run successfully and given the intended output

Annotations Used in Test classes

  1. @isTest(SeeAllData=true) : Use this annotation to grant test classes and individual test methods access to all data in the organization
  2. @isTest(SeeAllData=false) : All test methods and classes by default have this behavior
  3. @isTest(isParallel=true) : Use this annotation to indicate test classes that can run in parallel
  4. @isTest(isParallel=false) : This annotation will indicate that test class that cannot run in parallel
  5. @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.

Mock Class

Test Class

Additionally,

  1. Be as descriptive as possible while giving names to the test methods
    1. methodName + ExpectedOutput + WhenGivenWhatData
    2. testAccountTriggerItCreatesContactRecordWhenCreateContactCheckboxIsTrue
  2. 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
  3. 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