*EDIT-I have updated my code with more explanation and debugs showing what is printed and where execution unexpectedly exits without error. I am also only working with 1 test method for now. I am receiving debugs in the Trigger's first few lines, but the AggregateResultsList is always empty so the For-each loop never executes.

This Trigger will send an email message if an Account has 8 or more cases created within 7 days. Depending on the status of the four fields in the If/Else block will dictate the destination of the email. If the status is "Active" 1 email is sent to a set email address. If the status is "Implementation" then 2 emails are sent, addresses are grabbed from SOQL.

Any help is appreciated.

trigger CaseCountAlertTrigger on Case (before insert) {
List<String> emailAdds = new List<String>();                            // Holds '2' ToAddresses from Milestone1_project__c object
Set <Id> AcctIds = new Set <Id>();                                      //Holds Account Ids from this Case Trigger  
String messageToSend;                                                   //Email body sent in email (will be in HTML format)
Map < Id, String > accountIdEmailmessageMap = new Map < Id, String > (); // map of AccountId and Email body per Account/AccountId to be sent

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 Account.Name, AccountId
                                                    HAVING COUNT(Id) >= 8

System.debug('AggregateResult:  ' + AggregateResultList);  // debugs:    'AggregateResult: ()'  --emtpy aggregate list
  System.debug('Trigger Results' + Trigger.new);           // This line will print the Case that comes in as Trigger.New, debugs as expected.

//  ******** It seems to exit here***************

for (AggregateResult aggr: AggregateResultList){
                       messageToSend = 'You are receiving this email alert due to an account ';
                       messageToSend += 'activity rule has exceeded 8 cases created within 5 business days.<br><br>';
                       messageToSend += 'Please, follow up with the account and provide guidance and assistance.<br><br>';
                       messageToSend += '<b>Account Name:  </b>' + aggr.get('name') + '<br> <br>';
                       messageToSend +=  'Thank you, <br>';
                       messageToSend +=  'Salesforce Team';

             //Crete Map of <AccountId, Message to serve as body in Email
             //                         for each accountId>       
                Id accId = (Id) aggr.get('AccountId');
                accountIdEmailmessageMap.put(accId, messageToSend);

            //Create List of AccountId's to grab email addresses
            // from child Object for 'Implementation Status 



    List < Case > caseList = [SELECT Id, AccountId, Account.Name, Account.Eyefinity_EHR_Status__c,
                              Account.Eyefinity_PM_Status__c, Account.OfficeMate_Status__c,
                              FROM Case
                              WHERE AccountId IN: AcctIds];

    // SOQL to grab the four status fields on Account to check status either 'Active' or 'Implementation'
    // also grab two email addresses for use in ifElse block
    List<Account> accList = [SELECT Id, Name, Eyefinity_EHR_Status__c, Eyefinity_PM_Status__c,
                                    Project_Imp_Status__c, OfficeMate_Status__c,(select Client_Advisor_Email__c,
                                                                                 from Projects__r) 

                             FROM Account
                             WHERE Id IN :AcctIds];

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

    for (Account al: accList) {

        if (al.Eyefinity_EHR_Status__c == 'Active' ||
            al.Eyefinity_PM_Status__c == 'Active' ||
            al.Project_Imp_Status__c == 'Active'  ||
            al.OfficeMate_Status__c == 'Active') {

               // String messageBody = accountIdEmailmessageMap.get(al.accId);

                //Send Email to CustomerService if Active
                List<String> emailaddr = new List<String>();
                emailaddr.add('[email protected]');  

                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                mail.setSenderDisplayName(' Support');
                mail.Subject = 'Notification:  Account Case activity rule exceeded';

            else if (al.Eyefinity_EHR_Status__c == 'Implementation' ||
                     al.Eyefinity_PM_Status__c == 'Implementation' ||
                     al.Project_Imp_Status__c == 'Implementation' ||
                     al.OfficeMate_Status__c == 'Implementation'){
                String messageBody1 = accountIdEmailmessageMap.get(cl.AccountId);        

                System.debug('Accounts: ' + al);

               //Send email to Coordinator and Advisor if in Implementation

                for(Account a : accList)
                    for(Milestone1_Project__c p : a.Projects__r)

                Messaging.SingleEmailMessage amail = new Messaging.SingleEmailMessage();
                amail.Subject = 'Notification:  Account Case activity rule exceeded';



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


Test Case:

private class TestCaseHandlerAlert {

  @testSetup static void setup(){
      List<Account> testAccounts = new List<Account>();

        Account a = new Account();
            a.name = 'AccountEHRImplement';
            a.RecordTypeId = '01230000000v58OAAQ';
            a.Eyefinity_EHR_Status__c = 'Implementation';
            a.Tax_Id__c = '123456789';

        //Insert Account
            insert testAccounts;

         //Create User:  THis user will fill required fields on the Milestone1_Project1 allowing for a an email address to populate
        User tuser = new User(  firstname = 'tuserFname',
                            lastName = 'tuserLastname',
                            email = '[email protected]',
                            Username = '[email protected]',
                            EmailEncodingKey = 'ISO-8859-1',
                            Alias ='Blah',
                            TimeZoneSidKey = 'America/Los_Angeles',
                            LocaleSidKey = 'en_US',
                            LanguageLocaleKey = 'en_US',
                            ProfileId =[Select Id From Profile Where Name='Eyefinity Managers'].id
        insert tuser;

      //Create Project
        Milestone1_Project__c project1 = new Milestone1_Project__c();
            project1.Customer_Account__c = [Select Id FROM Account Where Name ='AccountEHRImplement'].id;
            project1.Name = 'triggerProject';
            project1.Client_Advisor__c = [Select Id FROM User Where Username ='[email protected]'].id;
            project1.Resource_Coordinator__c = [Select Id FROM User Where Username ='[email protected]'].id;  
            project1.RecordTypeId = '01214000001RYp7AAG';    
                insert project1;

    @isTest static void AccountEHRImplement (){

          //Create and insert more than more than 8 cases  
            List<Case> casestoInsert = new List<Case>();     
        for (Integer i=1; i<10; i++){
            Case cas1 = new Case();
                cas1.RecordTypeId = '01214000001NcOYAA0';
                cas1.AccountId = [Select Id FROM Account Where name ='AccountEHRImplement'].id;
                cas1.Origin = 'Phone';
                cas1.Impact__c = 'Low';
                cas1.Severity__c = 'Minor';
                cas1.Type = 'Bridge';

            insert casesToInsert; 

        System.debug('Expected: 2, actual: ' + Limits.getEmailInvocations());  

I can see the empty AggregateResult debug and the Trigger Results showing that Account that was created, but then nothing.


enter image description here

  • The async testing flag has nothing to do with the failures of these tests. What do your debug logs tell you about which branches are executing? I'd strongly recommend rethinking that runOnce pattern; I don't think it's at fault here but it causes lots of nasty behaviors.
    – David Reed
    Commented Nov 22, 2019 at 16:51
  • Another note, there is never any reason to have more than one email invocation from a single trigger. You should combine all of the messages and send them with one call to Messaging.sendEmail.
    – Adrian Larson
    Commented Nov 22, 2019 at 17:00
  • The log lines shown there are not coming from this trigger. Consider adding System.debug() calls to show where the path of execution goes, or use the Apex replay debugger.
    – David Reed
    Commented Nov 22, 2019 at 17:57

3 Answers 3


You're trying to query for records in a before insert trigger that are currently being processed by the trigger; i.e., have not yet been committed to the database and cannot be seen via SOQL.

Trigger is before insert:

trigger CaseCountAlertTrigger on Case (before insert) {

Your test class performs exactly one DML operation:

        insert casesToInsert; 

As a result, when you run your aggregate query:

List < AggregateResult > AggregateResultList = [SELECT AccountId, Account.Name name, COUNT(Id) co

there is nothing in the database to return. All N cases are in Trigger.new, but as it's before insert they have no Ids and haven't been committed yet.

Either (a) run the trigger after insert (which I think makes more sense in this use case) or (b) perform multiple DML inserts in your test case so that the responsive Cases will be committed to the database by the time you attempt to test the trigger's behavior.

  • I just realized that, thank you. In all of my copy/paste, I didn't look too close. Thanks
    – Tim
    Commented Nov 24, 2019 at 20:54

Put your assert after the stop test - start test stop test is supposed to enclose the asynchronous code that you want to run, and wait for it to complete.

Then you can make your assertion after it has finished.

  • Thank you for the response, but I am receving same result of `2 expected, 0 actual"
    – Tim
    Commented Nov 22, 2019 at 17:25
  • Could this be the issue - salesforce.stackexchange.com/questions/252796/… - a problem with assert either inside or outside the starttest/stop test. Also - is your trigger doing what you want it to do ? I'd assume that that SOQL query would only return accounts with 8 cases created in the last 7 days which are currently being inserted or updated. So, if you are inserting all cases at once, it'll work, otherwise not.
    – eaeaoo
    Commented Nov 22, 2019 at 19:55
  • I have debugged the number of emails inside and outside of the test start/stop. Both result in a 0 emails sent. Also, do you know what the SOQL would look like for cases added over a few days and not added at the same time?
    – Tim
    Commented Nov 22, 2019 at 21:09
  • Yes, according to the answer from the link above it isn't possible to test for sent emails in this way since if you put it inside the test start/stop emaithe assert can't measure the email (since it is a future method), while outside it is operating in a different context so it can't detect the sent emails - you have to rewrite to test in some other way.
    – eaeaoo
    Commented Nov 22, 2019 at 21:53
  • SOQL - extract the account ids from the trigger cases, stick it in a list or set, use your same query but remove the AND id IN :Trigger.new And replace with AND accountId IN accountList ?
    – eaeaoo
    Commented Nov 22, 2019 at 22:00

I have no idea how but issue resolved. This was after a recent Sandbox refresh. I copied/pasted and renamed the trigger. No issues. I don't have an explanation.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .