salesforce test class

What is The Use of Test Class in Salesforce | Developer Guide

Test Class

Testing is an important part of the Software Development Life Cycle (SDLC). Before moving the code in production, Salesforce ensures that your code has minimum 75% code coverage. This means that you have tested your code and it would not break in the production environment. For this you need to write a Test class for all your classes. For this Apex testing framework facilitates you to write the test class for Apex classes, triggers.

You write a test class to ensure that Apex Classes and triggers are working as expected, by testing it single and bulk record processing, for positive test cases and negative test cases. For this you also create the testing database.

dont miss out iconDon't forget to check out: Salesforce Apex Test Class Best Practices

For example:

Create a new class named ‘Demo’, inside it’s method you pass a list of those accounts whose rating you want to update to ‘Hot’.

Demo Class:

public class Demo {
    //method to update account’s rating to hot
    public static void accountUpdateWebsite(List<Account> accountsToUpdate){
        //Create a new List to update
        List<Account> updateAccountList = new List<Account>();
        //Iterate the list of account whose Rating you have to change to ‘Hot’       
        for(Account updateAccount: accountsToUpdate){
            updateAccount.Rating = 'Hot';
            updateAccountList.add(updateAccount); 
        }
        update updateAccountList;
    }
}

Now, create a new class with the name ‘DemoTest’:

@isTest public class DemoTest {
    //create test records for Account
    @testSetup static void testRecords(){
        List<Account> testAccountRecordList = new List<Account>();
        Account newAccountRecord1 = new Account(
            Name = 'Test Account 1',
            Website= 'https://www.test.com',
            Rating = 'Cold');
        Account newAccountRecord2 = new Account(
            Name = 'Test Account 1',
            Rating  = 'Warm');
        testAccountRecordList.add(newAccountRecord1);
        testAccountRecordList.add(newAccountRecord2);
        Test.startTest();
        insert testAccountRecordList;
        Test.stopTest();
    }
    @isTest static void accountRatingUpdate(){
        List<Account> listOfAccounts = [SELECT Id, Rating FROM Account WHERE Rating = 'Cold'];
        Demo.accountUpdateWebsite(listOfAccounts);
    }
}

As seen in the above example, @isTest at the starting of the test class; it denotes that this class is a test class and it won't count against the organisation’s total code limit.

By default test class does not access your organization's database i.e. whatever records you have in your organisation would not be seen by test class. To test our class, we need to create a testing database, for this we use @TestSetup.

In the above example, we are creating Account’s records. You should never use your org’s records. Create records  which have names like Test Account, for Email address [email protected] and so on.

As seen here, DML function is placed inside Test.start() and Test.stop(), what it does is, it provides a separate set of governor limits. Any DML operation or calling your Mock test should be placed inside this code. Each test method can use one Test.start() and Test.stop().

After creating testing records, you test the class methods. Here, we have queried the data, we pass this list into our class’s method and the test method will test whether the functionality you have written in the class would give the expected result with these test records or not. Click on Run Test on the upper right corner of the test class and then click on Test, you will see whether the test run is successful or it has failed.

This is a very simple example of test class here the Apex class method was not returning any value. If you have a method in your Apex class which does return a value, you should use System.assertsEqual() to check whether the expected value and actual values are equal. If the Method in this Demo class was to return the updated Account List, we would check it out in the test method using System.assertsEqual().

Demo Class:

public class Demo {
    public static List<Account> accountUpdateWebsite(List<Account> accountsToUpdate){
        List<Account> updateAccountList = new List<Account>();
        for(Account updateAccount: accountsToUpdate){           
            updateAccount.Rating = 'Hot';
            updateAccountList.add(updateAccount);            
        }
        System.debug('updateAccountList: '+updateAccountList);
        return updateAccountList;
    }
}
@isTest public class DemoTest {
    @testSetup static void testRecords(){
        /* Create test records for Account*/
        List<Account> testAccountRecordList = new List<Account>();                  
        Account newAccountRecord1 = new Account(
            Name = 'Test Account 1',
            Website= 'https://www.test.com',
            Rating = 'Cold');         
        Account newAccountRecord2 = new Account(
             Name = 'Test Account 1',
             Rating  = 'Warm');                  
        testAccountRecordList.add(newAccountRecord1);
        testAccountRecordList.add(newAccountRecord2);         
        Test.startTest();
        insert testAccountRecordList;
        Test.stopTest();
    }      
    @isTest static void accountRatingUpdate(){        
        List<Account> listOfAccounts = [SELECT Name, Rating FROM Account WHERE Rating = 'Cold'];
        System.assertEquals(listOfAccounts, Demo.accountUpdateWebsite(listOfAccounts));
    }
}

dont miss out iconCheck out another amazing blog by Krati here: Salesforce Governor Limits

Important points to remember about Test Classes are:

  • Test class must start with @isTest annotation
  • Don’t use (seeAllData = true), as it can access your org’s data.
  • Unit test is to test a particular piece of code working properly or not .
  • Unit test method takes no argument ,commits no data to database ,sends no email ,flagged with testMethod keyword .
  • To deploy to production at-least 75% code coverage is required
  • Do not focus on the  percentage of code coverage ,make sure that every use case should be covered including positive, negative,bulk and single record .
  • Single Action -To verify that the single record produces the correct and expected result .
  • Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
  • Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and did not go past the limit .
  • Negative Test Case :-Not to add future date , Not to specify negative amount.
  • Restricted User :-Test whether a user with restricted access used in your code .
  • Test class should be annotated with @isTest .
  • Test method should be static and have no void return type .
  • Test class and method default access is private ,no need to add access specifiers 
  • Test method can not be used to test web-service calls out . Please use mock test class.
  •  @testSetup to create test records once in a method  and use in every test method in the test class 
  • Use System.runAs() for testing different Users.

Popular Salesforce Blogs