Activity Forums Salesforce® Discussions How to cover try catch part in apex test class?

  • Ratnesh

    Member
    June 3, 2020 at 6:48 am

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

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos