function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jaishrijaishri 

hello , I want to write a test class to achieve 100 % code coverage for this below code can anyone help me to solve this problem i don't know how to write a test class for using this trigger

Trigger:
trigger CaseEmail on Case (after insert, after update,before delete) {
    
   If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter){//This line will allow only if the record is created or edited
	CaseEmailHandler.sendemailforInsrtupdate(Trigger.new);
   }
    if(Trigger.isDelete && Trigger.isBefore){// if the case is deleted we have to send an email so using this line and we used before because after deletion we cannot send email 
	CaseEmailHandler.sendemailfordelete(Trigger.old);
}
    }
 
Handler:
 
public class CaseEmailHandler {

    public static void sendemailforInsrtupdate(List<Case> caselist){
            Set<Id> conIds = new Set<Id>();
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    for (Case c: caselist) {
        conIds.add(c.ContactId);//adding the contact id so we can get the contact email for the case
   }
    Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);// quering the contact so we get the contact email
    
    for (Case c : caselist) {
        if (c.status == 'Closed') {// checking if the status is closed in case of create or edit scenerio
            Contact relatedCaseContact = conMap.get(c.ContactId);//getting the contact information related to particular case
            
            Messaging.SingleEmailMessage CaseNotificationmail = new Messaging.SingleEmailMessage();  
            CaseNotificationmail.setToAddresses(new List<String> { relatedCaseContact.Email });//adding to address
            CaseNotificationmail.setReplyTo('sample@salesforce.com');//adding reply to  address
            CaseNotificationmail.setSenderDisplayName('Salesforce');  //adding display name          
            
            CaseNotificationmail.setSubject(' Case Status updation  ' + 'Changed to ' + c.status + ' Case Number:' + c.CaseNumber);//adding subject
            CaseNotificationmail.setPlainTextBody(' Your case Status for Case Number: ' + c.CaseNumber + '  Related Case Contact:' +c.ContactId +' has been closed '); //adding body of the email
            mails.add(CaseNotificationmail); //adding the notification to the list so all the emails can be sent once
        }
        
        if(Trigger.isinsert && Trigger.isafter){// as we need a notification when a case is craeted
            Contact relatedCaseContact = conMap.get(c.ContactId);
                   Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
        mail.setToAddresses(new List<String> { relatedCaseContact.Email });
        mail.setSubject('New Case Create: '+ c.CaseNumber);
        String body = 'Case is created. Thank you for contacting us';
        mail.setHtmlBody(body);
        mails.add(mail);
        }
    }
 Messaging.sendEmail(mails);//sending the emails at once   
    }
    public static void sendemailfordelete(List<Case> caselist){
               Set<Id> conIds = new Set<Id>();
         for (Case c: caselist) {
        conIds.add(c.ContactId);
   }
      List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
         Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
    for (Case cs : caselist) {
         Contact relatedCaseContact = conMp.get(cs.ContactId);
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
        email.setToAddresses(new List<String> { relatedCaseContact.Email  });
        email.setSubject('Case Deleted');
        email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
        emails.add(email);
    }
    Messaging.sendEmail(emails);
    }
    
}

 
Best Answer chosen by jaishri
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Just a small change in the test class. In the stack exchange and your question here you have after update event as well so the email send were 2 but in the above shared code there is no after update context so only one email will be send and it is while delete so changes it based on that.
 
@isTest
public class CaseTriggerTest {
    @isTest
    public static void  testmethod1(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@testcontact.com';
        insert con;
        
        Case  cs= new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        
        Test.startTest();
        insert cs;
        Integer emailInvocations = Limits.getEmailInvocations();
        Test.stopTest();
        
        system.assertEquals(1, emailInvocations, 'An email should be sent');
        
        
    }
    
    @isTest
    public static void testmethod2(){
        contact con = new contact();
        con.LastName = 'Test';
        con.Email = 'test@test.com';
        insert con;
        
        Case cs = new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        insert cs;
        Test.startTest();
        delete cs;
        
        Integer emailInvocations = Limits.getEmailInvocations();
        Test.stopTest();
        
        system.assertEquals(1, emailInvocations, 'An email should be sent');
        
        
    }
}

If this solution helps mark it as best answer .

Thanks,
 

All Answers

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

I have answered the same question in stack exchange where you posted the same. 

https://salesforce.stackexchange.com/questions/374496/how-to-write-a-test-class-for-this-below-code-can-anyone-help-me/374523#374523

Please check there and let me know if you face any issues.

if that solution helps, Please mark it as best answer.

Thanks,
 
jaishrijaishri
Hi Sai ,
 Could you explain me this code line by line it will be more helpful for me
  
@isTest
    public class CaseEmailHandlerTest {
    @isTest
        public static void  testmethod1(){
            contact con = new contact();
            con.LastName = 'Test contact';
            con.Email = 'test@testcontact.com';
            insert con;
            
            Case  cs= new Case();
            cs.Status = 'New';
            cs.Origin = 'Phone';
            cs.ContactId =con.Id;
          
             Test.startTest();
             insert cs;   
             cs.status='Closed';
             update cs;
             delete cs;
            Test.stopTest();
    
        }
}

 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Please find the below explanation.
 
@isTest
public class CaseEmailHandlerTest {
@isTest
    public static void  testmethod1(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@testcontact.com';
        insert con;//Creating a contact with lastname and email field
        
        Case  cs= new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
      
         Test.startTest();
          insert cs;// Creating a case with that contact id and status as new 
        Integer emailInvocations = Limits.getEmailInvocations();// getting number of email invocations happened because of case creation
    Test.stopTest();

    system.assertEquals(1, emailInvocations, 'An email should be sent');// As only one email should be sent so comparing that with no og invocations
       

    }
    
    @isTest
    public static void testmethod2(){
        contact con = new contact();
        con.LastName = 'Test';
        con.Email = 'test@test.com';
        insert con;//Creating a contact with lastname and email field
        
        Case newCase = new Case();
        newCase.Status = 'New';
        newCase.Origin = 'Phone';
        newCase.ContactId =con.Id;
      insert newCase;// Creating a case with that contact id and status as new 
         Test.startTest();
           newCase.status='Closed';
        update newcase;// Updating the case status as closed
        delete newcase;// deleting the case

        Integer emailInvocations = Limits.getEmailInvocations();// getting number of email invocations happened because of case creation
    Test.stopTest();

    system.assertEquals(2, emailInvocations, 'An email should be sent');// As only 2 email should be sent(one for updating and another for deleting) so comparing that with no of invocations
        

    }
}

If this solution helps, please mark it as best answer.

Thanks,
 
jaishrijaishri
hi sai ,there is some issue with this code the data is not inserted in salesforce and it is also not sending a email i also saw the debug log it is not showing data what we are inserted when case is created or deleted it send a email using test class
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

From the test classes the emaila wont be send. It is just to check the code is working fine or not. The records created or updated wont be availble in salesforce org nor the emails sent as well. So we are checking using system.asserts. After the test class runs all the created records will be deleted. 

It is the functionality of the test class.

If this answers your question please mark it as best answer.

Thans,


Thanks,
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Did this answer your dobt or do you need any clarifiations.

Thanks,
 
jaishrijaishri
Hi sai,
           the status for above code Assertion failed:- An email it should be sent Expected:  2,Actual:  4
      how i understand the code is working properly and give me correct output

 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Can you check if there is any trigger on case sending the emails.

As per the code it should send only two emails(once updated and once deleted) but it is sending 4 emails so the asserion is failing.

Thanks,
 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

For checking the test class you can also turn off other triggers so it won't impact this functionality and let me know if this works as expected. 

I hope you are using the same test class which I shared in stack exchange.

Thanks,
 
jaishrijaishri
Hi Sai , I turnoff the other triggers also and i write the same code which you shared in stack exchange. the status for above code Assertion failed:- An email it should be sent Expected:  2, Actual:  1
Sai PraveenSai Praveen (Salesforce Developers) 
Hi jai,

Can you share your apex class and test class once so I can check it .

Thanks,
 
jaishrijaishri
Trigger

trigger CaseTrigger on Case (after insert,before delete) {
    
    If( Trigger.isinsert && Trigger.isafter){
        CaseHelper.afterInsert(Trigger.new);
    }
    if(Trigger.isDelete && Trigger.isBefore){
        
        CaseHelper.beforeDelete(Trigger.old);
    }
}
 
Helper

public class CaseHelper {
    public static void afterInsert(List<Case> caselist){
        Set<Id> conIds = new Set<Id>();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        for (Case c: caselist) {
            conIds.add(c.ContactId);
        }
        Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
        for (Case c : caselist) {
            Contact CaseContact = conMap.get(c.ContactId);
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
            mail.setToAddresses(new List<String> { CaseContact.Email });
            mail.setSubject('New Case Create '+  c.CaseNumber);
            mail.setPlainTextBody('Case is created Thank you for contacting us');
            mails.add(mail);
            
        }
        Messaging.sendEmail(mails); 
    }
    public static void beforeDelete(List<Case> caselist){
        Set<Id> conIds = new Set<Id>();
        for (Case c: caselist) {
            conIds.add(c.ContactId);
        }
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        Map<Id, Contact> conMp = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Id In :conIds]);
        
        for (Case cs : caselist) {
            Contact caseContact = conMp.get(cs.ContactId);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            
            email.setToAddresses(new List<String> { caseContact.Email  });
            email.setSubject('Case Deleted');
            email.setPlainTextBody('This message is to alert you that the Case number' + cs.CaseNumber + ' has been deleted. Thank you for contacting us.');
            emails.add(email);
        }
        Messaging.sendEmail(emails);
    }
    
    
}
 
Test Class

@isTest
public class CaseTriggerTest {
    @isTest
    public static void  testmethod1(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@testcontact.com';
        insert con;
        
        Case  cs= new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        
        Test.startTest();
        insert cs;
        Integer emailInvocations = Limits.getEmailInvocations();
        Test.stopTest();
        
        system.assertEquals(1, emailInvocations, 'An email should be sent');
        
        
    }
    
    @isTest
    public static void testmethod2(){
        contact con = new contact();
        con.LastName = 'Test';
        con.Email = 'test@test.com';
        insert con;
        
        Case cs = new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        insert cs;
        Test.startTest();
        cs.status='Closed';
        update cs;
        delete cs;
        
        Integer emailInvocations = Limits.getEmailInvocations();
        Test.stopTest();
        
        system.assertEquals(2, emailInvocations, 'An email should be sent');
        
        
    }
}

 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Just a small change in the test class. In the stack exchange and your question here you have after update event as well so the email send were 2 but in the above shared code there is no after update context so only one email will be send and it is while delete so changes it based on that.
 
@isTest
public class CaseTriggerTest {
    @isTest
    public static void  testmethod1(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@testcontact.com';
        insert con;
        
        Case  cs= new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        
        Test.startTest();
        insert cs;
        Integer emailInvocations = Limits.getEmailInvocations();
        Test.stopTest();
        
        system.assertEquals(1, emailInvocations, 'An email should be sent');
        
        
    }
    
    @isTest
    public static void testmethod2(){
        contact con = new contact();
        con.LastName = 'Test';
        con.Email = 'test@test.com';
        insert con;
        
        Case cs = new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        insert cs;
        Test.startTest();
        delete cs;
        
        Integer emailInvocations = Limits.getEmailInvocations();
        Test.stopTest();
        
        system.assertEquals(1, emailInvocations, 'An email should be sent');
        
        
    }
}

If this solution helps mark it as best answer .

Thanks,
 
This was selected as the best answer
jaishrijaishri
Thank you for help
jaishrijaishri
hi Sai, for create a case and delete a case using test class in trigger can we get the email from above code using Messaging.SingleEmailMessage
Sai PraveenSai Praveen (Salesforce Developers) 
Hi,

As confirmed earlier you cannot get any email or create records using test class. Test clases are like unit test scripts written to check the functionality.

Thanks,
 
jaishrijaishri
hi Sai , there is also one test class here we get email
  @isTest static void setup() {
        // Create common test accounts
        List<Case> testCase = new List<Case>();
        for(Integer i=0;i<1;i++) {
            Case cs = new Case();  
            cs.Origin='Email';
            cs.Subject='Test Case';
            cs.Status = 'Closed case';
            cs.To_Address__c= 'test@test.com';
            testCase.add(cas);
        }
        insert testCase;  
        
        Delete testCase;
        
    }  
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

Can you share entire test class so I can check. This is just one method on the test class.

Thanks,
 
jaishrijaishri
@isTest
public class CaseTriggerHandler_Test_class{

     @isTest static void setup() {
        // Create common test accounts
        List<Case> testCase = new List<Case>();
        for(Integer i=0;i<1;i++) {
            Case cas = new Case();  
            cas.Origin='Email';
            cas.Subject='Test Case';
            cas.Status = 'Closed case';
            cas.To_Address__c = 'test@test.com;
            testCase.add(cas);
        }
        insert testCase;  
        
        Delete testCase;
        
    }

 
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Jai,

There is no contact information on the test class I did not get how will this send an email to the contact email address. If you are trying with another apex class and test class can you put it as new question as this thread is so long to verify any answer.

Thanks,
 
jaishrijaishri
Hi Sai ,
      Yes I have shared as new question