+ Start a Discussion
Makam RuthvikMakam Ruthvik 

how to cover test class for try catch block Messaging..sendEmail

Hi,

 

 
        try {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });

}
        } catch (Exception e) {
            System.debug('Exception'+e.getMessage());
            throw e;
        }

I can' t get the code coverage for catch block.

 

Tried the below,

try {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
            
            if(Test.isRunningTest()) {
    throw new EmailException('Email Exception occurred for testing'); 
}
        } catch (Exception e) {
            System.debug('Exception'+e.getMessage());
            throw e;
        }

Getting 100% coverage but the test class is failing.

 

Please help me out here

Suraj Tripathi 47Suraj Tripathi 47

Hi,

I have tested your code and it is not showing any error. Your code coverage is 80% if you call simply like that

global class YAauraApex {
Public static void data(){
        try {
             Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
             String [] toAddresses = new String[] {'abc@gmail.com'};
             email.setToAddresses(toAddresses);
             email.setSubject('Subject');
             email.setPlainTextBody('Body');	
             
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        } catch (Exception e) {
            System.debug('Exception'+e.getMessage());
            throw e;
        }
    }
}

 


Test Class:

@isTest
public class YAauraApexTest {
    @isTest
    static void callData(){
                    Test.startTest();
                    YAauraApex.data();
                    Test.stopTest();
         
    }
}

Please mark it as the Best Answer if it helps you.

Thank You