Salesfore Apex Test Class Best Pracitces

Salesfore Apex Test Class Best Pracitces

Apex Unit Tests

The Apex testing framework enables you to write and execute tests for your Apex classes and triggers on the Lightning Platform. Apex unit tests ensure high quality for your Apex code and let you meet requirements for deploying Apex.

Salesforce recommends that you write tests for the following:

Single action

Test to verify that a single record produces the correct, expected result.

Bulk actions

Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. You must test not only the single record case, but the bulk cases as well.

Positive behavior

Test to verify that the expected behavior occurs through every expected permutation, that is, that the user filled out everything correctly and did not go past the limits.

Negative behavior

There are likely limits to your applications, such as not being able to add a future date, not being able to specify a negative amount, and so on. You must test for the negative case and verify that the error messages are correctly produced as well as for the positive, within the limits cases.

Restricted user

Test whether a user with restricted access to the sObjects used in your code sees the expected behavior. That is, whether they can run the code or receive error messages.

1. Test Class Utility

Use utility class for creating records for the test class.

Sample Utility class:

@isTest  
public with sharing class TestDataFactory {  

    public static List < Lead > createLeadGenLeads( 
        Integer intCount, 
        Boolean doInsert 
    ) {  

        List < Lead > listLeads = new List < Lead >();  
        Id leadGenRecordTypeId = 
            Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(
                'Lead Generation'
            ).getRecordTypeId();  

        for ( Integer i = 0; i < intCount; i++ ) {  

            Lead newLead = new Lead() ;  
            newLead.FirstName = 'Test ' + i;  
            newLead.LastName = 'Sample ' + i;  
            newLead.Company = 'Clayton Test ' + i;  
            newLead.Status = 'Contacted';  
            newLead.RecordTypeId = leadGenRecordTypeId;  
            /* 
            Add all fields required for Lead Gen 
            */  
            listLeads.add(newLead);  

        }  

        if ( doInsert )  
            insert listLeads;  

        return listLeads;  

    }  

    public static List < Lead > createRetailLeads( 
        Integer intCount, 
        Boolean doInsert 
    ) {  

        List < Lead > listLeads = new List < Lead >();  
        Id retailRecordTypeId = 
            Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get(
                'Retail'
            ).getRecordTypeId();  

        for ( Integer i = 0; i < intCount; i++ ) {  

            Lead newLead = new Lead() ;  
            newLead.FirstName = 'Test ' + i;  
            newLead.LastName = 'Sample ' + i;  
            newLead.Company = 'Claton Sample ' + i;  
            newLead.Status = 'Contacted';  
            newLead.RecordTypeId = retailRecordTypeId;  
            /* 
            Add all fields required for Retail 
            */  
            listLeads.add(newLead);  

        }  

        if(doInsert)  
            insert listLeads;  

        return listLeads;  

    }  

}  

To call the utility class methods in the test class, check the below sample code.

List < Lead > listLeadGenLeads = TestDataFactory.createLeadGenLeads(3, true);//This will insert and return the records.

List < Lead > listRetailLeads = TestDataFactory.createRetailLeads(3, false);//This will just return the 3 leads without any DML.

2. Set Up Test Data for an Entire Test Class in Salesforce

To Set Up Test Data for an Entire Test Class in Salesforce, @testSetup is used. @testSetup avoids creation of same set of records to be used in different test methods in the same test class.

To Set Up Test Data for an Entire Test Class in Salesforce, @testSetup is used. @testSetup avoids creation of same set of records to be used in different test methods in the same test class.

Sample Test Class:

@isTest  
private class CommonTestSetup {  

    /* Method to setup data */  
    @testSetup static void setup() {  

        /* Create common test Accounts */  
        List < Account > testAccts = new List < Account >();  
        for ( Integer i = 0; i<2; i++ ) {  
        testAccts.add(new Account(Name = 'TestAcct'+i));  
        }  
        insert testAccts;       

        /* Create common test Contacts */  
        List < Contact > testContacts = new List < Contact >();  
        for ( Integer i = 0; i<2; i++ ) {  
            testContacts.add(
                new Contact(
                    FirstName = 'TestAcct'+i, 
                    LastName = 'TestAcct'+i
                )
            );  
        }  
        insert testContacts;    
    }  

    @isTest static void testMethod1() {  

        /* Testing Method with Accounts and Contacts */  

    }  

    @isTest static void testMethod2() {  

        /* Testing Method with Contacts */  

    }  

}  

3. Use Test.startTest() and Test.stopTest()

Test.startTest() and Test.stopTest() are very useful when your test class hits Salesforce Governor Limits.

The code inside Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits. As a good practice, make sure initializing the variables, fetching records, creating and updating records are coded before Test.startTest() and Test.stopTest() and calling the controllers for code coverage is done inside Test.startTest() and Test.stopTest(). The code before Test.startTest() and after Test.stopTest() have new set of Salesforce Governor Limits and code between Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits.

Sample Test Class:

private class TestClass {  

    static testMethod void test() {  

        /* 
            Declare the variables, 
            Fetch the required records, 
            Create and Update sample records 
        */  

        Test.startTest();  
            /* 
                Call the controller for code coverage 
            */  
        Test.stopTest();  

    }  

}  

Note:

Any code that executes after the stopTest method is assigned to the original limits that were in effect before startTest was called.

4. System.assert, System.assertEquals and System.assertNotEquals

System.Assert accepts two parameters, one (mandatory) which is the condition to test for and the other a message (optional) to display should that condition be false.

System.AssertEquals and System.AssertNotEquals both accepts three parameters; the first two (mandatory) are the variables that will be tested for in/equality and the third (optional) is the message to display if the assert results in false.

Both are used in Test Class for “Positive Case Testing” and “Negative Case Testing” with single and multiple records.

Sample Code:

Trigger:

trigger AccountTrigger on Account ( before insert ) {  

    for ( Account acct : trigger.new ) {  

        if ( acct.Name == 'Test Account' )  
            acct.Description = 'Test';  

    }  

} 

Test Class:

@isTest  
private class SampleTestClass {  

    static testMethod void insertAcctTest() {  

        Account acc = new Account(
            Name = 'Test Account'
        );  
        insert acc;  
        acc = [ 
            SELECT Description 
            FROM Account 
            WHERE Id = : acc.Id 
        ];  
        System.assertEquals(
            'Test', 
            acc.Description
        );  

    }  

}  

In the above example, the expected Description of the Account is ‘Test’. If any other additional processes like Workflow Field update, Process Builder, etc updates the Description other than ‘Test’, it will throw an error and fails the test method. This will make sure that developed code is working as expected.

Opposite to System.assertEquals() is System.assertNotEquals().

5. runAs Method

Use the runAs method to test your application in different user contexts.

The system method runAs enables you to write test methods that change either the user contexts to an existing user or a new user. When running as a user, all of that user’s record sharing is then enforced. You can only use runAs in a test method. The original system context is started again after all runAs test methods complete.

The following items use the permissions granted by the user specified with runAs running as a specific user:

Dynamic Apex

Classes using with sharing or without sharing

Shared records

The original permissions are reset after runAs completes.

The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.

In the following example, a new test user is created, then code is run as that user, with that user’s record sharing access:

@isTest  
private class TestRunAs {  

    public static testMethod void testRunAs() {  

        String uniqueUserName = 
            'standarduser' + 
            DateTime.now().getTime() + 
            '@testorg.com';  

        Profile p = [ 
            SELECT Id 
            FROM Profile 
            WHERE Name = 'Standard User' 
        ];  

        User u = new User(
            Alias = 'standt', 
            Email='[email protected]',  
            EmailEncodingKey = 'UTF-8', 
            LastName = 'Testing', 
            LanguageLocaleKey = 'en_US',  
            LocaleSidKey = 'en_US', 
            ProfileId = p.Id,  
            TimeZoneSidKey = 'America/Los_Angeles',  
            UserName = uniqueUserName
        );  

        System.runAs(u) {  

            // The following code runs as user 'u'  
            System.debug(
                'Current User: ' + 
                UserInfo.getUserName()
            );  
            System.debug(
                'Current Profile: ' + 
                UserInfo.getProfileId()
            );  

        }  
    }  

}  

6

. Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on.

7. Test the classes in your application individually. Never test your entire application in a single test.

8. Use Mock responses for testing callouts. Check Appendix B and C for sample test classes.

9. Avoid using seeAllData=true.

10. Avoid hard coding Ids, etc.

12. Adding SOSL Queries to Unit Tests 

To ensure that test methods always behave in a predictable way, any Salesforce Object Search Language (SOSL) query that is added to an Apex test method returns an empty set of search results when the test method executes. If you do not want the query to return an empty list of results, you can use the Test.setFixedSearchResults system method to define a list of record IDs that are returned by the search. All SOSL queries that take place later in the test method return the list of record IDs that were specified by the Test.setFixedSearchResults method. Additionally, the test method can call Test.setFixedSearchResults multiple times to define different result sets for different SOSL queries. If you do not call the Test.setFixedSearchResults method in a test method, or if you call this method without specifying a list of record IDs, any SOSL queries that take place later in the test method return an empty list of results.

The list of record IDs specified by the Test.setFixedSearchResults method replaces the results that would normally be returned by the SOSL query if it were not subject to any WHERE or LIMIT clauses. If these clauses exist in the SOSL query, they are applied to the list of fixed search results.Note:

1. Although the record may not match the query string in the FIND clause, the record is passed into the RETURNING clause of the SOSL statement.
2. If the record matches the WHERE clause filter, the record is returned. If it does not match the WHERE clause, no record is returned.

Sample code:

Apex Controller:

public class SOSLController {  
  
    public static List < List < SObject > > searchAccountContactLead( 
        String strSearch 
    ) {  
      
        String searchQuery = 'FIND \'' 
            + strSearch 
            + '*\' IN ALL FIELDS RETURNING Account( Id, Name WHERE Industry = \'Apparel\' ), Contact, Lead';   
        return search.query( 
            searchQuery 
        );  
      
    }  
      
} 

Test class:

@isTest  
private class SOSLControllerTest {  
  
    static testMethod void testSOSL() {  
      
        Account acc = new Account( Name = 'Testing', Industry = 'Banking' );  
        insert acc;  
        List < List < SObject > > searchResults = SOSLController.searchAccountContactLead( 'Sample' );  
        List < Account > listAccount = searchResults.get( 0 );  
        system.assertEquals( 0, listAccount.size() );//Size will be zero since setFixedSearchResults is not set  
        Id [] fixedSearchResults = new Id[1];  
        fixedSearchResults[0] = acc.Id;  
        Test.setFixedSearchResults( fixedSearchResults );  
        searchResults = SOSLController.searchAccountContactLead( 'Sample' );  
        listAccount = searchResults.get( 0 );  
        system.assertEquals( 0, ( (List<Account>)searchResults.get( 0 ) ).size() );//Size will be still zero since WHERE condition fails for account  
        acc.Industry = 'Apparel';  
        update acc;  
        searchResults = SOSLController.searchAccountContactLead( 'Sample' );  
        listAccount = searchResults.get( 0 );  
        system.assertEquals( 1, listAccount.size() );//Size will be one since Account WHERE conditions succeeds  
      
    }  
      
} 

Appendix – A – Sample Test Class for Schedulable_Class

@istest  
public with sharing class SampleTest {  

    static testmethod void testSample() {  

        Test.startTest();  
        Schedulable_Class  obj = new Schedulable_Class();  
        obj.execute(
            null
        );  
        Test.stopTest();  

    }  

}  

Appendix – B – Test class for HTTPCallouts in Salesforce

Sample HTTPCallout Class:

@isTest  
global class AnimalLocatorMock implements HttpCalloutMock {  

    global HTTPResponse respond(
        HTTPRequest request
    ) {  

        HttpResponse response = new HttpResponse();  
        response.setHeader(
            'Content-Type', 
            'application/json'
        );  
        response.setBody(
            '{"animal": {"id":2, "name":"Test"}}'
        );  
        response.setStatusCode(
            200
        );  
        return response;   

    }  

}  

Sample HTTP Mock Callout Class:

@isTest   
private class AnimalLocatorTest {  

    static testMethod void testPostCallout() {  

    Test.setMock(
        HttpCalloutMock.class, 
        new AnimalLocatorMock()
    );    
    String strResp = 
        AnimalLocator.getAnimalNameById(
            2
        );  

    }  
    
}  

Test Class:

@isTest  
global class AnimalLocatorMock implements HttpCalloutMock {  

    global HTTPResponse respond(
        HTTPRequest request
    ) {  

        HttpResponse response = new HttpResponse();  
        response.setHeader(
            'Content-Type', 
            'application/json'
        );  
        response.setBody(
            '{"animal": {"id":2, "name":"Test"}}'
        );  
        response.setStatusCode(
            200
        );  
        return response;   

    }  

}

Appendix – C – Test class for SOAP Callout in Salesforce

Class generated from WSDL:

//Generated by wsdl2apex  

public class ParkService {  

    public class byCountryResponse {  

        public String[] return_x;  
        private String[] return_x_type_info = new String[]{'return','http://parks.services/',null,'0','-1','false'};  
        private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};  
        private String[] field_order_type_info = new String[]{'return_x'};  

    }  
    public class byCountry {  

        public String arg0;  
        private String[] arg0_type_info = new String[]{'arg0','http://parks.services/',null,'0','1','false'};  
        private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};  
        private String[] field_order_type_info = new String[]{'arg0'};  

    }  
    public class ParksImplPort {  

        public String endpoint_x = 'https://th-apex-soap-service.herokuapp.com/service/parks';  
        public Map<String,String> inputHttpHeaders_x;  
        public Map<String,String> outputHttpHeaders_x;  
        public String clientCertName_x;  
        public String clientCert_x;  
        public String clientCertPasswd_x;  
        public Integer timeout_x;  
        private String[] ns_map_type_info = new String[]{'http://parks.services/', 'ParkService'};  
        public String[] byCountry(String arg0) {  

            ParkService.byCountry request_x = new ParkService.byCountry();  
            request_x.arg0 = arg0;  
            ParkService.byCountryResponse response_x;  
            Map<String, ParkService.byCountryResponse> response_map_x = new Map<String, ParkService.byCountryResponse>();  
            response_map_x.put('response_x', response_x);  
            WebServiceCallout.invoke(  
            this,  
            request_x,  
            response_map_x,  
            new String[]{endpoint_x,  
            '',  
            'http://parks.services/',  
            'byCountry',  
            'http://parks.services/',  
            'byCountryResponse',  
            'ParkService.byCountryResponse'}  
            );  
            response_x = response_map_x.get('response_x');  
            return response_x.return_x;  

        }  

    }  

}

Class making use of WSDL generated Class:

public class ParkLocator {  

    public static List < String > country(
        String Country
    ) {  

        ParkService.ParksImplPort obj =   
        new ParkService.ParksImplPort();  
        return obj.byCountry( Country );  

    }  

}  

Mock for test class:

@isTest  
global class ParkServiceMock implements WebServiceMock {  

    global void doInvoke(  
        Object stub,  
        Object request,  
        Map<String, Object> response,  
        String endpoint,  
        String soapAction,  
        String requestName,  
        String responseNS,  
        String responseName,  
        String responseType
    ) {  

        ParkService.byCountryResponse response_x = 
            new ParkService.byCountryResponse();  
        response_x.return_x = 
            new List < String > {
                'a', 
                'b'
            };  
        response.put(
            'response_x', 
            response_x
        );   

    }  

}  

Test Class:

@isTest  
private class ParkLocatorTest {  

    @isTest static void testCallout() {        

        Test.setMock(
            WebServiceMock.class, 
            new ParkServiceMock()
        );  
        List < String > result = ParkLocator.country(
            'Test'
        );  

    }  

}  

Appendix – D – Test class for Email Services classes in Apex

In the test class, follow the below

1. Create Messaging.InboundEmail.

2. Create Messaging.InboundEnvelope.

3. Pass them to handleInboundEmail() method of Messaging.InboundEmailHandler class.

Sample Test Class Code:

Messaging.InboundEmail email = 
    new Messaging.InboundEmail() ;  
Messaging.InboundEnvelope env = 
    new Messaging.InboundEnvelope();  

email.subject = 'Test';  
email.fromname = 'Test Test';  
env.fromAddress = '[email protected]';  
email.plainTextBody = 'Test';  

CreateLeadInboundHandler emailProcess = 
    new CreateLeadInboundHandler();  
emailProcess.handleInboundEmail(
    email, 
    env
);  

Appendix – E – Test code coverage for private methods in Apex

TestVisible annotation allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes.

Sample Class:

public class TestVisibleExample {  

    // Private member variable  
    @TestVisible private static Integer recordNumber = 1;  

    // Private method  
    @TestVisible private static void updateRec() {  
    }  

} 

Test Class:

@isTest  
private class TestVisibleExampleTest { 

    @isTest static void test1() {  

        // Accessing private variable annotated with TestVisible  
        Integer i = 
            TestVisibleExample.recordNumber;  
        System.assertEquals(
            1, 
            i
        );  

        // Accessing private method annotated with TestVisible  
        TestVisibleExample.updateRecord();  

    }  

}  

Leave a Reply