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 have code in which i'm inserting a bulk of data of 200 records in test class of case can anyone tell me where i'm doing wrong it showing error:- inserted failed

Test Class 

@isTest
    public static void testmethod3(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'sample@sample.com';
        insert con;
        List<Case> caseList = new List<Case>();
        for(Integer i=1; i<=200 ; i++){
            Case cs = new Case();
            cs.Status = 'New';
            cs.Origin = 'Phone';
            cs.ContactId =con.Id;
            caseList.add(cs);
        }
        
          Test.startTest();
          insert caseList;
          Test.stopTest();
    
}

 
Best Answer chosen by jaishri
CharuDuttCharuDutt
Hii Jaishri
Try Below Code Coverage 95%
Made Small Changes In Main Class In Highlight
@isTest
public class CaseEmailHandlerTest {
    @isTest
    public static void testmethod1(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@test.com';
        insert con;
        List<Case> caseList = new List<Case>();
        for(Integer i=1; i<=200 ; i++){
        Case cs = new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        caseList.add(cs);
        
        Case cs2 = new Case();
        cs2.Status = 'Closed';
        cs2.Origin = 'Phone';
        cs2.ContactId =con.Id;
        caseList.add(cs2);
        }
        
        
        Test.startTest();
        insert caseList;
        Test.stopTest();
        
    }
    @isTest
    public static void testmethod3(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@test.com';
        insert con;
        List<Case> caseList = new List<Case>();
        
        Case cs = new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        caseList.add(cs);
        
        Case cs2 = new Case();
        cs2.Status = 'Closed';
        cs2.Origin = 'Phone';
        cs2.ContactId =con.Id;
        caseList.add(cs2);
        
        
        Test.startTest();
        insert caseList;
        delete caseList;
        Test.stopTest();
        
    }
}



MAIN CLASS:
public class CaseEmailHandler {
    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); //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);
            }
        }
        
        try {
            if(!test.isRunningTest()){
            Messaging.sendEmail(mails);
            }//sending the emails at once 
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
        
        
    }
    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 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);
        }
         try {
            if(!test.isRunningTest()){
            Messaging.sendEmail(emails);
            }//sending the emails at once 
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }
    
}
Please Mark It As Best Answer If It Helps
Thank You!

All Answers

CharuDuttCharuDutt
Hii Jaishri
Refresh The Dev Console And Run Test Again 
Please Mark It As Best Answer If It Helps
Thank You!
jaishrijaishri
Hi CharuDutt,
      It is not working
AnkaiahAnkaiah (Salesforce Developers) 
Hi Jaishri,

Can you check, is there any mandaory fields are missing in the test data for conact & case objects.

Thanks!!
jaishrijaishri
Hi Ankaiah,
                     I have write the mandatory field in test class 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Jaishri,

Can you share the error on which line you are getting?

Thanks!!
jaishrijaishri
User-added image
AnkaiahAnkaiah (Salesforce Developers) 
Hi Jaishri,

As per your screenshot, it seems like you have an issue with  sendemail.

Open that log and check where exactly its failing in the caseTrigger.

Thanks!!
jaishrijaishri
trigger CaseEmail on Case(after insert, after update, before delete) {

    If((Trigger.isUpdate || Trigger.isinsert) && Trigger.isafter) { 
        CaseEmailHandler.afterInsert(Trigger.new);
    }
    if (Trigger.isDelete && Trigger.isBefore) { 
        CaseEmailHandler.beforedelete(Trigger.old);
    }
}
 
public class CaseEmailHandler {
    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); //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 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 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);
    }

}
 
@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;
        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');
        

    }
     @isTest
    public static void testmethod3(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@test.com';
        insert con;
        List<Case> caseList = new List<Case>();
        for(Integer i=1; i<=200 ; i++){
            Case cs = new Case();
            cs.Status = 'New';
            cs.Origin = 'Phone';
            cs.ContactId =con.Id;
            caseList.add(cs);
        }
        
          Test.startTest();
          insert caseList;
          Test.stopTest();
    
}
}
I have put these 3 codes can anyone tell why the bulk of records is not inserting here
 
CharuDuttCharuDutt
Hii Jaishri
Try Below Code Coverage 95%
Made Small Changes In Main Class In Highlight
@isTest
public class CaseEmailHandlerTest {
    @isTest
    public static void testmethod1(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@test.com';
        insert con;
        List<Case> caseList = new List<Case>();
        for(Integer i=1; i<=200 ; i++){
        Case cs = new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        caseList.add(cs);
        
        Case cs2 = new Case();
        cs2.Status = 'Closed';
        cs2.Origin = 'Phone';
        cs2.ContactId =con.Id;
        caseList.add(cs2);
        }
        
        
        Test.startTest();
        insert caseList;
        Test.stopTest();
        
    }
    @isTest
    public static void testmethod3(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'test@test.com';
        insert con;
        List<Case> caseList = new List<Case>();
        
        Case cs = new Case();
        cs.Status = 'New';
        cs.Origin = 'Phone';
        cs.ContactId =con.Id;
        caseList.add(cs);
        
        Case cs2 = new Case();
        cs2.Status = 'Closed';
        cs2.Origin = 'Phone';
        cs2.ContactId =con.Id;
        caseList.add(cs2);
        
        
        Test.startTest();
        insert caseList;
        delete caseList;
        Test.stopTest();
        
    }
}



MAIN CLASS:
public class CaseEmailHandler {
    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); //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);
            }
        }
        
        try {
            if(!test.isRunningTest()){
            Messaging.sendEmail(mails);
            }//sending the emails at once 
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
        
        
    }
    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 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);
        }
         try {
            if(!test.isRunningTest()){
            Messaging.sendEmail(emails);
            }//sending the emails at once 
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }
    
}
Please Mark It As Best Answer If It Helps
Thank You!
This was selected as the best answer
jaishrijaishri
hi CharuDutt, It is showing error :- Assertion Failed : An email should be send: Expected :2 ,Actual : 0
CharuDuttCharuDutt
Hii Jashri Your Class Doesn't Have Any Assertion Must Firing From Another Class Please Check that Class
jaishrijaishri
Hi CharuDutt,
             I have only one test class in my org
  Thanks