Example:
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();
}
}