Skip to main content
Cyndie Wandia (N/A) ha preguntado en #Apex
Please help me write a test class for an apex trigger that sends an email when a contact is created.

 

trigger EmailContact on Contact (after insert) {

List<Messaging.SingleEmailMessage> emailList= new List<Messaging.SingleEmailMessage>();

EmailTemplate emailTemplate = [Select Id,Subject,Description,HtmlValue,DeveloperName,Body from EmailTemplate where name='Contract Signed Thank you'];

for(Contact conObj:Trigger.new){

if (conObj.Email != null) {

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setTargetObjectId(conObj.Id);

mail.setSenderDisplayName('System Administrator');

mail.setUseSignature(false);

mail.setBccSender(false);

mail.setSaveAsActivity(true);

mail.setTemplateID(emailTemplate.Id);

mail.toAddresses = new String[]{conObj.Email};

emailList.add(mail);

}

}

if(emailList.size()>0){

Messaging.SendEmailResult[] results = Messaging.sendEmail(emailList);

if (results[0].success)

{

System.debug('The email was sent successfully.');

} else {

System.debug('The email failed to send: '+ results[0].errors[0].message);

}

}

}

 

This is what i have so far. i get an error that lines 9&15 are missing ','

@isTest private class EmailContactTestClass { static testMethod void validateEmailContact() { Contact c = new Contact(LastName='Test',Email='test@test.org'); System.debug(c.LastName); insert c; System.assertEquals(0, Limits.getEmailInvocations(); c = [SELECT id FROM Contact WHERE LastName ='Test' limit 1]; System.assertEquals(1, Limits.getEmailInvocations(); } }

 
4 respuestas
  1. 16 may 2022, 3:00
    Hi,

    The closing parenthesis is missing in System.assertEquals(1, Limits.getEmailInvocations() at both the places because of that you are getting compile-time error.

    Try this 

    @isTest private class EmailContactTestClass {

        static testMethod void validateEmailContact() { 

            Contact c = new Contact(LastName='Test',Email='test@test.org'); 

            System.debug(c.LastName); 

            insert c; 

            System.assertEquals(0, Limits.getEmailInvocations()); 

            c = [SELECT id FROM Contact WHERE LastName ='Test' limit 1]; 

            System.assertEquals(1, Limits.getEmailInvocations()); 

        } 

    }

    Kindly mark as best answer if it helps.

    Thanks

    Shubham Jain
0/9000