+ Start a Discussion
rajubalajirajubalaji 

How to write a test class for catch exception?

Hi Everyone

Anyone have idea please help me guide for test class for catch (Exception ex) below code:

catch (Exception ex) {
                String fileId;
                if (Request.Header != null && Request.Header.FileID != null) {
                    fileId = Request.Header.FileID;
                }
                else {
                    fileId = 'Unknown';
                }
                StarTransactionDetails.CreateInboundTransactionRequest(Request.Header.TransactionType, fileId, 'Exception', reqBody, ex.getMessage(), parentId, null, null, environmentCode);
                if(Request != null && Request.Header != null){
                    responseJSON = InboundTransactionResponse.GetErrorResponse(Request.Header.TransactionType, Request.Header.TimeStamp, Request.Header.FileID, null, 'Error', '0036', ex.getMessage());
                }else{
                    responseJSON = ex.getMessage();
                }

Please anyone know about that please help me.

Thanks,
Raju
AnudeepAnudeep (Salesforce Developers) 
Hi Raju, 

I am posting a sample code here. You can relate it with your code

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

}

I also recommend reviewing this post

Let me know if it helps