Test class to cover Catch block in Salesforce

Test class to cover Catch block in Salesforce

Sample Class:

public class LeadCreation {
    public Lead objLead;
    public String lastName;
    public LeadCreation() {
        
    }
    public PageReference newLead() {
        objLead = new Lead(Company = ‘Test’, LastName = lastName, Status = ‘Open – Not Contacted’);
        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() {
        LeadCreation obj = new LeadCreation();
        try {
            obj.newLead();
        } catch(DMLException e) {
            system.assertEquals(e.getMessage().contains(‘Last Name’));
        }
        obj.lastName = ‘Testing’;
        obj.newLead();
    }
}


Note:


This code is written in a way to just cover catch block.

Cheers!!!

Leave a Reply