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
Timothy SmithTimothy Smith 

Creating Test class - CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

My Trigger sends an email message when an Account has 8 cases created within 7 days. The Case object has a Lookup relationship to the Milestone1__project__c object has a relationship name Parent_Project_If_Applicable__r.

If any of these fields are equal to 'Live - Closed Project':
Parent_Project_if_applicable__r.Implementation_status__c Parent_Project_if_applicable__r.PM_Implementation_Status__c Parent_Project_If_Applicable__r.RCM_Implementation_Status__c

Then the Email is sent to the address in the IF BLock. Any other value the email is sent through the Else Block.
Every test pass except setup. I am trying to create a user (preferably two) with email addresses. I found that the fields Parent_Project_if_applicable__r.Resource_Coordinator_Email__c and Parent_Project_if_applicable__r.Client_Advisor_Email__c are formula fields grabbing the email in a formula that looks like this Client_Advisor__r.Email and Resource_Coordinator_Email__c .
How do I add Insert the user so that I can test that the emails would go to the right destination?
 
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CaseHandlerCountAlert: execution of AfterInsert

caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_EMAIL_ADDRESS, Email address is invalid: null: [toAddresses, null]

Trigger.CaseHandlerCountAlert: line 78, column 1: []

Test Class:
 
@isTest
private class TestCaseHandlerAlert {

    @TestSetup static void setup(){
       //Create user to populate field Resource Coord. and Implementation Spec.

        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        User u = new User(Alias = 'testER', Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='standarduser101@testorg.com');

        insert u;
        system.debug(u.email);

       // Create and Insert 2 Accounts

        Account a = new Account();
        Account b = new Account();
            a.name = 'testacct21';
            b.name = 'testacct31';



 //Set Contact id to variables
 //  Id userIDToInsert = [select id from User Where username='standarduser101@testorg.com'].id;


  // Create Milestones

 //This Milestone will fire the If Block    
  Milestone1_Project__c project1 = new Milestone1_Project__c();
        project1.Name = 'triggertestLIVE';
        project1.RCM_Implementation_Status__c = 'LIVE - CLOSED PROJECT';
        project1.PM_Implementation_Status__c= 'RETURNED SOFTWARE';
        project1.Implementation_Status__c= 'RETURNED SOFTWARE';
        project1.Resource_Coordinator__c = u.Id;
        project1.Client_Advisor__c = u.Id;


 Milestone1_Project__c project = new Milestone1_Project__c();
        project.Name = 'triggertest21';
        project.RCM_Implementation_Status__c = 'RETURNED SOFTWARE';
        project.PM_Implementation_Status__c= 'RETURNED SOFTWARE';
        project.Implementation_Status__c= 'RETURNED SOFTWARE';
        project1.Resource_Coordinator__c = u.Id;
        project1.Client_Advisor__c = u.id;


     //Insert Account
    insert a;
    insert b;
    //Insert Project
    insert project;
    insert project1;

    //Create 10 Cases associated with Project

    List<Case> casesToInsert = new List<Case>();
    List<Case> casesToInsert1 = new List<Case>();

        for (Integer i=1; i<10; i++){

            Case c = new Case();
                c.AccountId = a.id;
                c.Origin = 'Phone';
                c.Impact__c = 'Low';
                c.Severity__c = 'Minor';
                c.Type = 'Bridge';
                c.Parent_Project_if_applicable__c = project1.id;

            casesToInsert.add(c);
         }

        for (Integer i=1; i<10; i++){  
        Case c1 = new Case();
        c1.AccountId = b.id;
        c1.Origin = 'Phone';
        c1.Impact__c = 'Low';
        c1.Severity__c = 'Minor';
        c1.Type = 'Bridge';
        c1.Parent_Project_if_applicable__c = project.id;

        casesToInsert.add(c1);
    }          



      insert casesToInsert; 
      insert casesToInsert1;

    }



@isTest static void DontSendNotLimit (){
        // Do not send, not enough Cases need 8 
        List<Case> testCases = [SELECT Id FROM Case WHERE Account.Name='testacct21' LIMIT 5];
        List<Case> insertCases = new List<Case>();   

      Test.startTest();
        insert insertCases;
        System.debug('Should be 0 emails sent: ' + Limits.getEmailInvocations());
      Test.stopTest();
    }

@isTest static void SendElseBlock (){
        // Else BLock Fires - 2 emails sent 
        List<Case> testCases = [SELECT Id FROM Case WHERE Account.Name='testacct21' LIMIT 8];
        List<Case> insertCases = new List<Case>();   

      Test.startTest();
        insert insertCases;
        System.debug('Should be 3: ' + Limits.getEmailInvocations());
      Test.stopTest();
    }   



@isTest static void SendRCMiFBlock (){
        // Fires the If BLock 1/3
        List<Case> testCases = [SELECT Id FROM Case WHERE Account.Name='testacct31' LIMIT 8];
        List<Case> insertCases = new List<Case>();  
        for(Case cas :testCases ){

                insertCases.add(cas);
            } 

      Test.startTest();
        insert insertCases; 
      Test.stopTest();
    }

    @isTest static void SendPMiFBlock (){
        // Fires the If BLock 2/3
        List<Case> testCases = [SELECT Id FROM Case WHERE Account.Name='testacct31' LIMIT 8];
        List<Case> insertCases = new List<Case>();  
        for(Case cas :testCases ){

                cas.Parent_Project_if_applicable__r.PM_Implementation_Status__c = 'LIVE - CLOSED PROJECT';
                insertCases.add(cas);
            } 

      Test.startTest();
        insert insertCases; 
      Test.stopTest();
    }

    @isTest static void SendIMPiFBlock (){
        // Fires the If BLock 3/3
        List<Case> testCases = [SELECT Id FROM Case WHERE Account.Name='testacct31' LIMIT 8];
        List<Case> insertCases = new List<Case>();  
        for(Case cas :testCases ){
                cas.Parent_Project_if_applicable__r.Implementation_Status__c= 'LIVE - CLOSED PROJECT';
                insertCases.add(cas);
            } 

      Test.startTest();
        insert insertCases; 
      Test.stopTest();
    }


}

Trigger:
 
trigger CaseHandlerCountAlert on Case (after insert, after update) {

//Case trigger that will send email alert when 8 cases are created within 7 days.
String messageToSend;
List <String> ListOfMessages = new List <String>();
Set <Id> AcctIds = new Set <Id>();
String messageBody;

List < AggregateResult > AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co
                                                FROM Case
                                                WHERE CreatedDate = LAST_N_DAYS:7 AND Id IN :Trigger.New
                                                GROUP BY AccountId, Account.Name
                                                HAVING COUNT(Id) >= 8
                                               ];

Map < Id, String > accountIdEmailmessageMap = new Map < Id, String > ();

for (AggregateResult aggr: AggregateResultList) {
    String messageToSend = 'Account name: ' + aggr.get('name') +
        ' has ' + (Integer) aggr.get('co') +
        ' cases opened in the last 8 days.';
    Id accId = (Id) aggr.get('AccountId');
    accountIdEmailmessageMap.put(accId, messageToSend);
    AcctIds.add(accId);
}


List < Case > caseList = [SELECT Id, AccountId, Account.Name, Parent_Project_if_applicable__r.Implementation_status__c,
                          Parent_Project_if_applicable__r.PM_Implementation_Status__c,
                          Parent_Project_if_applicable__r.RCM_Implementation_Status__c,
                          Parent_Project_if_applicable__r.Resource_Coordinator_Email__c,
                          Parent_Project_if_applicable__r.Client_Advisor_Email__c                      
                          FROM Case
                          WHERE AccountId IN: AcctIds];

List<Messaging.SingleEmailMessage> lstASingleEmailMessage = new List<Messaging.SingleEmailMessage>();
List<Messaging.SingleEmailMessage> lstBSingleEmailMessage = new List<Messaging.SingleEmailMessage>();

for (Case cl: caseList) {

    if (cl.Parent_Project_if_applicable__r.Implementation_status__c == 'Live - Closed Project' ||
        cl.Parent_Project_if_applicable__r.PM_Implementation_Status__c == 'Live - Closed Project' ||
        cl.Parent_Project_If_Applicable__r.RCM_Implementation_Status__c == 'Live - Closed Project') {

            String messageBody = accountIdEmailmessageMap.get(cl.AccountId);

            List<String> emailaddr = new List<String>();
            emailaddr.add('GlobalEmailAddress@domain.com');  

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setSenderDisplayName('Support');
            mail.setToAddresses(emailaddr);   
            mail.Subject = 'Multiple cases created alert message';
            mail.setPlainTextBody(messageBody);
            lstASingleEmailMessage.add(mail);




        }else{
            String messageBody1 = accountIdEmailmessageMap.get(cl.AccountId);        

            List<String> emailAdds = new List<String>();
            emailAdds.add(cl.Parent_Project_if_applicable__r.Resource_Coordinator_Email__c);
            emailAdds.add(cl.Parent_Project_if_applicable__r.Client_Advisor_Email__c); 

            Messaging.SingleEmailMessage amail = new Messaging.SingleEmailMessage();
            amail.SetSenderDisplayName('Support');
            amail.setToAddresses(emailAdds);
            amail.Subject = 'Multiple cases created alert message';
            amail.setPlainTextBody(messageBody1);
            lstBSingleEmailMessage.add(amail);


        }  
}
Messaging.SendEmailResult[] r = Messaging.sendEmail(lstASingleEmailMessage);   
Messaging.SendEmailResult[] rb = 

Messaging.sendEmail(lstBSingleEmailMessage);
}


​​​​​​​