+ Start a Discussion
Arnas BaronasArnas Baronas 

How to write apex test class for SingleEmailMessege

Hello Developers,
I'm new at apex development, maybe someone could explain me how write a test for this type of apex class or give me some kind of example ?

public class emailSending {
public string toMail { get; set;}
public string ccMail { get; set;}
public string repMail { get; set;}
    public void sendMail(){
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
string[] to = new string[] {toMail};
string[] cc = new string[] {ccMail};
email.setToAddresses(to);
if(ccMail!=null && ccMail != '')
     email.setCcAddresses(cc);
if(repmail!=null && repmail!= '')
    email.setInReplyTo(repMail);
email.setSubject('Test Mail');
email.setHtmlBody('Hello, <br/><br/>This is the test mail that you generated. <br/>The Email Id for which this mail was generated by '+toMail+'<br/><br/>Regards<br/> Developer');
try{
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
}catch(exception e){
apexpages.addmessage(new apexpages.message(apexpages.severity.error,e.getMessage()));
}
toMail = '';
ccMail = '';
repMail = '';
}
}
Best Answer chosen by Arnas Baronas
MKRMKR
Hi,

You can use Limits.getEmailInvocations and ApexPages.getMessages to verify the results. Like this:
 
@isTest
private class emailSendingTest {
	
    @isTest
    private static void testEmailSendingPositive() {
        emailSending emailSend = new emailSending();
        emailSend.toMail = 'test.address@email.for';
        emailSend.ccMail = 'test.address2@email.for';
        emailSend.sendMail();
        System.assertEquals(1,Limits.getEmailInvocations());
    }
    
    @isTest
    private static void testEmailSendingNegative() {
        emailSending emailSend = new emailSending();
        emailSend.toMail = 'test.address@email.for';
        emailSend.repMail = 'INVALID_VALUE';
        emailSend.sendMail();
        System.assertEquals(0,Limits.getEmailInvocations());
        System.assertEquals(1, ApexPages.getMessages().size());
    }
    
}

Regards,
Mkr