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
Christian ØelundChristian Øelund 

Test Class Error

Hey I'm really new to coding
Then i run the test class, it gived me this error;


<span unselectable="on" "="" style="display: block; padding: 3px 4px; overflow: hidden; margin-left: 0px; color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: normal; white-space: nowrap; widows: 1; background-color: rgb(218, 240, 249);">Stack Trace
Class.Trigger_Task_Send_Email_Test1.emailTest_single: line 15, column 1

My trigger
trigger Trigger_Task_Send_Email on Task (before update) {
    // Don't forget this- all triggers in SF are bulk triggers and so
    // they can fire on multiple objects. So you need to process objects
    // in a FOR loop.
    Set<Id> createdbyIds = new Set<Id>();
   
    for(Task tsk: Trigger.New)
        createdbyIds.add(tsk.createdbyId);
   
    // Build a map of all users who are assigned the tasks.
    Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :createdbyIds]);
    for(Task tsk : Trigger.New)
    {
        User theUser = userMap.get(tsk.createdbyId);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {theUser.Email};
        mail.setToAddresses(toAddresses);    // Set the TO addresses
        mail.setSubject('A task created by you has been updated');    // Set the subject
        // Next, create a string template. Specify {0}, {1} etc. in place of actual values.
        // You can replace these values with a call to String.Format.
        String template = 'Hello {0}, \nYour task has been modified. Here are the details: \n\n';
        template+= 'Subject - {1}\n';
        template+= 'Due Date - {2}\n';
        String duedate = '';
        if (tsk.ActivityDate==null)
            duedate = '';
        else
            duedate = tsk.ActivityDate.format();
        List<String> args = new List<String>();
        args.add(theUser.Name);
        args.add(tsk.Subject);
        args.add(duedate);
        
       
        // Here's the String.format() call.
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
}

My test class (gived me 96% code coverage, but makes the above error)
@isTest
private class Trigger_Task_Send_Email_Test1 {
    static testMethod void emailTest_single() {
        Task testTask = new Task(
            Subject = 'Test Task 1',
            ActivityDate = Date.today()
        );
        insert testTask;

        Integer emailsSentPre = Limits.getEmailInvocations();

        Test.startTest();

        testTask.Subject = 'Test Task 2';
        update testTask;

        Test.stopTest();

        Integer emailsSentPost = Limits.getEmailInvocations();
        Integer emailsSent = emailsSentPost - emailsSentPre;

        System.assertEquals(1, emailsSent, 'We should have only sent one email');
    }
}

Their must be an error en my test class, but can't figure out what. Can somebody help me please.

Thanks
 
pti69pti69
hi

hmm not sure but I think there is a limit to the number of SingleEmailMessage[] you can do. 10 or something like that. After that it will give an error. Because you put that in a for loop it could be called more than 10 times.

maybe you can try this:

After line  05     Set<Id> createdbyIds = new Set<Id>();
Add this--> List <Messaging.SingleEmailMessage> listofMails = new List <Messaging.SingleEmailMessage>();

comment out 39   Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
and replace with--> listofMails.add(mail);  /* Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});*/

After line 40  }
add this -->Messaging.sendEmail(listoMails);



 
JayantJayant
Looks okay to me.
What's the exception message you are getting ? The stack trace does not show the error message in the snapshot.

Is it some kind of assignment (for e.g. on Trailhead) that's checking for optimum code ? Just guessing it as the comments say things like -

"// Don't forget this- all triggers in SF are bulk triggers and so
03     // they can fire on multiple objects. So you need to process objects
04     // in a FOR loop."

If it is then you need to optimize your trigger by using setTargetObjectId instead of toAddresses, which is the preferred way of sending emails to Users, Contacts or Leads. For others or if you want to send same email to multiple recipients(to/cc/bcc), you may use toAddresses. Emails sent using setTargetObjectId do not count against the daily limit for SingleEmailMessages that we can send (currently 1000) while those sent using toAddresses count against this limit.
Christian ØelundChristian Øelund
trigger Trigger_Task_Send_Email on Task (before update) {
    // Don't forget this- all triggers in SF are bulk triggers and so
    // they can fire on multiple objects. So you need to process objects
    // in a FOR loop.
    Set<Id> createdbyIds = new Set<Id>();
    List <Messaging.SingleEmailMessage> listofMails = new List <Messaging.SingleEmailMessage>();

    for(Task tsk: Trigger.New)
        createdbyIds.add(tsk.createdbyId);
   
    // Build a map of all users who are assigned the tasks.
    Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :createdbyIds]);
    for(Task tsk : Trigger.New)
    {
        User theUser = userMap.get(tsk.createdbyId);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {theUser.Email};
        mail.setToAddresses(toAddresses);    // Set the TO addresses
        mail.setSubject('A task created by you has been updated');    // Set the subject
        // Next, create a string template. Specify {0}, {1} etc. in place of actual values.
        // You can replace these values with a call to String.Format.
        String template = 'Hello {0}, \nYour task has been modified. Here are the details: \n\n';
        template+= 'Subject - {1}\n';
        template+= 'Due Date - {2}\n';
        String duedate = '';
        if (tsk.ActivityDate==null)
            duedate = '';
        else
            duedate = tsk.ActivityDate.format();
        List<String> args = new List<String>();
        args.add(theUser.Name);
        args.add(tsk.Subject);
        args.add(duedate);
        
       
        // Here's the String.format() call.
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        listofMails.add(mail);  /* Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});*/
        Messaging.sendEmail(listofMails);
    }
}
It did'nt solve the problem giving me the same error :(
JayantJayant
Can you try moving Test.startTest() to the beginning before you create the Task instance ?

Also, you should call Limits methods with in startTest and stopTest as the governor limits are reset at startTest and primary purpose of startTest and stopTest is to have a dedicated set of limits (for things that happen between them).
pti69pti69
hey the Messaging.sendEmail(listofMails);
should be outside the for loop.
Christian ØelundChristian Øelund
Maybe i'm writing it wrong, but nothing seems to work for me.