How to write code for try catch in test class 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(), e.getMessage());
        }
        obj.lastName = 'Testing';
        obj.newLead();
    }
}

Note:

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

Cheers!!!

No comments:

Post a Comment