Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Mastering Exception Handling in Salesforce: Executing Exceptions in Apex Unit Tests

Here are three demonstrations of how we can cover the Apex Test Exception block. 

Here goes the first base class:

1.1 AccountControllerData.cls
The provided Salesforce Apex class, AccountControllerData, has a static method acInsert that attempts to insert an Account object into the database. If an exception occurs during the insertion, it catches the exception
public with sharing class AccountControllerData {
    public static void acInsert(Account ac){

        try{
            insert ac;
        }
        catch(Exception e){
            //for checking whether the line is executed or not
            String justToCheckWhetherTheExceptionIsHandled = 'Exception handled';
        }
    }
}

1.2 AccountControllerDataTest.cls

  1. It creates an Account object without providing the required ‘Name’ field.
  2. It then calls the acInsert method from the AccountControllerData class and catches any exception that might occur.
  3. It uses System.debug to log the error message from the caught exception.
  4. Finally, it asserts that the Id of the Account the object is null, indicating that the insertion should have failed due to the missing ‘Name’ field.
@isTest
public with sharing class AccountControllerDataTest {
    @isTest static void testAc() {
    Account acWithoutName = new Account();

    try {
        //not providing the required field 'Name', hehe
        AccountControllerData.acInsert(acWithoutName);
    } catch (Exception e) {
        System.debug('Error is: '+e.getMessage());
    }

    System.assert(acWithoutName.Id == null,'Id should be null');
  }
}

2.1 AccountControllerForced.cls

  1. The Salesforce Apex class AccountControllerForced defines a static method acInsert that doesn’t perform any database operations (DML) but contains random code.
  2. It checks if it’s running in a test context using Test.isRunningTest() and throws an AuraHandledException with an empty message if it is.
  3. While it catches exceptions, it doesn’t provide meaningful error handling or perform any useful actions, making it appear as a template or placeholder for testing purposes.
public with sharing class AccountControllerForced {
    public static void acInsert(){
        //just some random codes, No DMLs...................
        try {
	    	String shref = 'shref';
	    	//Some randome codes goes brrrr....................
		if(Test.isRunningTest())
		{
		   throw new AuraHandledException('');
		}
        } catch (Exception e) {
		//for checking whether the line is executed or not
            	String justToCheckWhetherTheExceptionIsHandled = 'Exception handled';
		}
    }
}

2.2 AccountControllerForcedTest.cls

  1. This is a Salesforce Apex test class named AccountControllerForcedTest used for testing the AccountControllerForced class.
  2. The testAc test method calls the acInsert method from the AccountControllerForced class and catches any exceptions that may be thrown during its execution. It logs the error message using System.debug.
  3. The test includes a System.assert(true) statement, which always evaluates to true, ensuring that the test method completes without errors. However, this test primarily focuses on checking exception handling and doesn’t include specific assertions related to the behavior of the code being tested.
@isTest
public with sharing class AccountControllerForcedTest {
        @isTest static void testAc() {
        try {
            AccountControllerForced.acInsert();
        }catch (Exception e) {
            System.debug('Error is: '+e.getMessage());
        }
        
        System.assert(true);
    }
}

3.1 AccountControllerUser.cls

  1. The Salesforce Apex class AccountControllerUser includes a static method acInsert, which is designed to insert an Account record into the database.
  2. Before attempting the insertion, it checks if the ‘Name’ field of the ‘Account’ object is createable using Schema.sObjectType.Account.fields.Name.isCreateable(). If it’s createable, it assigns the name ‘Maria Account’ to the ac object.
  3. It then tries to insert the ac object into the database. If an exception occurs during the insertion process, it is caught, but the catch block doesn’t provide meaningful error handling; it only assigns a string value to a variable without taking specific corrective actions for the exception. Typically, you would handle exceptions more effectively in a production Salesforce application, such as logging the error or notifying users.
public with sharing class AccountControllerUser {
    public static void acInsert(){
        Account ac = new Account();

        if(Schema.sObjectType.Account.fields.Name.isCreateable()) {
            ac.Name = 'Maria Account';
        }

        try{
            insert ac;
        }
        catch(Exception e){
            //for checking whether the line is executed or not
            String justToCheckWhetherTheExceptionIsHandled = 'Exception handled';
        }
    }
}

3.2 AccountControllerUserTest.cls

  1. The test method testAc performs the following actions:
    • It first fetches the Salesforce profile with the name ‘Minimum Access – Salesforce’ and assigns its ID to the variable p.
    • It creates a new User (usr) with specific attributes, including the profile ID (ProfileId) set to the previously fetched profile ID.
    • The User record is inserted into the system.
    • It then uses system.runAs(usr) to run the test code under the context of the newly created user, simulating their actions.
  2. Inside the system.runAs(usr) block, it tries to execute the acInsert method from the AccountControllerUser class. Any exception that may occur during this execution is caught in a catch block, and the error message is logged using System.debug.
  3. After executing the test code within the system.runAs(usr) block, it asserts that the usr.Id is not null, ensuring that the user insertion was successful. This assertion confirms that the user was created and the test scenario was executed.

Note: This test is primarily focused on checking how the AccountControllerUser class behaves under the context of a specific user profile with minimal access rights and how it handles exceptions, as indicated by the try and catch blocks.

@isTest
public with sharing class AccountControllerUserTest {
    @isTest static void testAc() {
    String minimumAS = 'Minimum Access - Salesforce';

    //fetching Minimum Access profile
    Id p = [SELECT Id,
                   Name
            FROM   Profile
            WHERE  Name=:minimumAS].id;

    User usr = new User(LastName = 'LIVESTON',
                        FirstName='JASON',
                        Alias = 'jliv',
                        Email = '[email protected]',
                        Username = '[email protected]',
                        ProfileId = p,
                        TimeZoneSidKey = 'GMT',
                        LanguageLocaleKey = 'en_US',
                        EmailEncodingKey = 'UTF-8',
                        LocaleSidKey = 'en_US'
    );
    insert usr;

    system.runAs(usr) {
        try{
        AccountControllerUser.acInsert();
        }
        catch(Exception e){
            System.debug('Error is: '+e.getMessage());
        }
    }
    //AccountControllerUser.acInsert();
    System.assert(usr.Id != null,'User insertion is failed');
  }
}

These are the 3 ways we can utilize Apex Test Class executions. Feel free to share your observations/ suggestions on it.

Share your love

Leave a Reply

Your email address will not be published. Required fields are marked *