0

I don't know, how to fix it: my messages are in List.

Helper:

public with sharing class Helper {

public static void afterInsert(List<P__c> newList, Map<ID, P__c> newMap){

    List<Id> userIds = new List<Id>();
    EmailTemplate emailTemplate = [SELECT Id FROM emailTemplate WHERE Name = 'Email'];
    Messaging.Email[] messages = new Messaging.Email[0];

    for(User u : [SELECT Id FROM User WHERE UserRole.Name = 'Manager']){
            userIds.add(u.Id);
        }

    for(P__c p : newList){

        Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
    mail.templateId = emailTemplate.Id;
        mail.targetObjectIds = userIds;
        mail.saveAsActivity = false;
    messages.add(mail);
    }
    Messaging.sendEmail(messages);
}

Trigger:

trigger EmailTrigger on P__c (after insert) {


if (Trigger.isAfter && Trigger.isInsert) {
    Helper.afterInsert(Trigger.new, Trigger.newMap);
} 
}

Bulk-test:

@isTest
static void sendEmailBulkTest(){
    insert createUser();

    for(Integer i=0; i<11; i++){
        insert p();
    }
    Integer emailInvocations = Limits.getEmailInvocations();
    system.assertEquals(emailInvocations, 11);

}

And I get msg "System.LimitException: Too many Email Invocations: 11". How can I fix it?

5

Your entire test method is treated as a single transaction. Since you have the insert inside the for loop, you are executing sendMail 11 times in this single transaction, and thus you get the error.

You need to create a list of P__c records and then insert the list outside the for loop.

  • But if I add it into the list in test method, I'll need to write System.assertEquals(emailInvocations, 1); Is it bulk too? – Монте Кристо Sep 15 '18 at 4:22
  • Yes you will, and presumably that is what the test aims to show that when may records are added only one send is done (rather than a send per record). By the way, I couldn't use an @YourName in this comment so you might change YourName to something that this mechanism works for. – Keith C Sep 15 '18 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.