Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Navigating Salesforce Excellence
Navigating Salesforce Excellence
Here are three demonstrations of how we can cover the Apex Test Exception block.
Here goes the first base 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 exceptionpublic 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
Account object without providing the required ‘Name’ field.acInsert method from the AccountControllerData class and catches any exception that might occur.System.debug to log the error message from the caught exception.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
AccountControllerForced defines a static method acInsert that doesn’t perform any database operations (DML) but contains random code.Test.isRunningTest() and throws an AuraHandledException with an empty message if it is.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
AccountControllerForcedTest used for testing the AccountControllerForced class.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.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
AccountControllerUser includes a static method acInsert, which is designed to insert an Account record into the database.Schema.sObjectType.Account.fields.Name.isCreateable(). If it’s createable, it assigns the name ‘Maria Account’ to the ac object.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
testAc performs the following actions:
p.usr) with specific attributes, including the profile ID (ProfileId) set to the previously fetched profile ID.system.runAs(usr) to run the test code under the context of the newly created user, simulating their actions.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.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 = 'hs@hasanstudies.com',
Username = 'hs@hasanstudies.com',
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.