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

(489)

Written by 

I am Sakthivel Madesh, a certified Salesforce Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 13x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply