Salesforce Apex Test Class

Get Started with Salesforce Apex Test Class | The Developer Guide

Testing is a crucial part of the Salesforce development life cycle. Whenever we do code in Salesforce, we cannot send it directly to the production. We need to do testing in the same way a QA will do but by writing some code. This is possible by using test classes. Results of  these test classes are calculated in percentage. If the test result percentage is 75% or more than 75% then we can send the code to production, otherwise we cannot. This is done so that our code does not break in any situation.

Developers do testing (also known as unit tests) to ensure that the code is functional and to ensure that the project is running smoothly without errors. Unit tests are done for following items/components:-

  • Apex class
  • Apex batch/queueable/future method
  • Apex triggers
  • Custom controllers

Advantages of Test class

  • Test class ensures that our code works as expected.
  • We can perform bulk tests using test class.
  • High quality codes are delivered to production orgs.
  • Reduces the cost of bugs

dont miss out iconDon't forget to check out: Testing HTTP Callouts using SFCraft MockServer: Part 1 | Salesforce Help Guide

Methods Used in Test Classes

  • Test.startTest() and Test.stopTest()
    startTest() - This the point at which our test actually begins.
    stopTest() - This is the point at which our test stops.
  •  System.Assert() 
  • System.AssertEquals()
  • System.runAs()
  • Test.isRunningTest()
  • Test.LoadData()

Best Practices for Writing Test Class 

  • Test class code minimum required coverage is 75% but ideally, we should try for 100%.
  • We should try with positive as well as negative scenarios.
  • Test class should be created with the “load testing” aspect, by creating a list of data and then inserting and then checking how things are working. Instead of going with a single record, create a list then add records, and then apply DML statements.
  • Always use @isTest before test class.
  • Try to avoid using existing data, create new data in the test class.
  • Always use Test.StartTest() and Test.StopTest() in every test function.
  • If we need to test multiple scenarios, try to use different methods as possible than adding all the logic in one method, because this helps to have good control over the test class execution, and when we want to see which method is giving what percentage result, we can comment on other methods and see the impact.
  • Always bypass those things like integration calls or validations for email sending actions in test class as you want this to happen only in real-time execution, not in testing.

dont miss out iconCheck out an amazing Salesforce video tutorial here: Modern App Development On Salesforce - Apex Testing

Basic Sample Code for Apex Test Class

Apex handler class for campaign field update:

public class CampaignFieldUpdate {
    public static void FieldUpdate(list<campaign> campaignlist){ //created a list of campaigns in method
        for(campaign VarCampaign:campaignlist){ //applied for loop
            if(VarCampaign.Generate_Webform__c==True){ //applied if condition
                VarCampaign.Web_form_Url__c='https://www.algoworks.com/contact-us/'; //if condition true then field will be updated with this message
            }
        }
    }
}

Apex trigger for the above hander class:

trigger CampaignFieldUpdateTrigger on Campaign (before insert,before update) {
if(Trigger.isinsert || Trigger.isupdate){
        CampaignFieldUpdate.FieldUpdate(trigger.new);
    }
}

Test class for the above trigger:

@istest
public class CampaignFieldUpdateTestClass {
public static testmethod void CampaignTest(){
        campaign VarCampaign=new campaign(name='Test campaign',Generate_Webform__c=true);
        test.startTest();        
        insert VarCampaign;       
        test.stopTest();                
    }
}

 

Responses

Popular Salesforce Blogs