Code Coverage in Try Catch Block in Apex Test Class in Salesforce

Sample Apex class and Apex Test class for your reference to increasing the code coverage in Try Catch Block.

Sample 1:

Main Class (Lead Creation Example to cover the catch block)

public class leadCreationController {
public Lead objLead;
public String lastName;
public LeadCreation() {

}
public PageReference newLead() {
objLead = new Lead(Company = ‘TheBlogReaders’, LastName = ‘TRB’, Status = ‘Open’);
try {
insert objLead;
PageReference pg = new PageReference(‘/’ + objLead.Id);
pg.setRedirect(true);
return pg;
} catch(DMLException e) {
return null;
}
}
}

 

Test Class: 

@isTest

private class LeadCreationTest {

@isTest static void leadTest() {
leadCreationController obj = new leadCreationController();
try {
obj.newLead();
} catch(DMLException e) {
system.assertEquals(e.getMessage().contains(‘TRB’));
}
obj.lastName = ‘Testing’;
obj.newLead();
}

}

 

Sample 2:

Main Class (Account Creation Example to cover the catch block)

public class AccountCreation{
 public Account objAcc;
 public String name;
 public AccountCreation() {
 }
 public Account newAccount() {
 objAcc = new Account(Name = name, AccountNumber = 'ACC1000', Type = 'Customer - Direct');
 try {
    insert objAcc;
    return objAcc;
 }catch(DMLException e) {
    return null;
 }
 }
}

Test Class:
@isTest
public class AccountCreateTest{
    public static testmethod void AccTest(){ 
        AccountCreation objAcc = new AccountCreation(); 
        try{ 
            objAcc.newAccount(); 
        }catch(DMLException e){
           system.assertEquals(e.getMessage(), e.getMessage()); 
        }
        objAcc.name = 'Test Account';
        objAcc.newAccount();
    }
}

Reference:
https://trailhead.salesforce.com/modules/apex_testing
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_code_coverage_intro.htm

Written by 

Salesforce MVP | Lightning Champion | 17x Salesforce Certified | Application Architect | 7x Trailhead Ranger | Techforce Services | Australia

Leave a Reply

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

*