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
SriniSrini 

I want to know how to write the test class for Email notification when delegated task is complete

Best Answer chosen by Srini
Himanshu Jasuja 9Himanshu Jasuja 9
In your code you are checking that the task current status should be completed and task old status should not be completed like below:

if(tsk.Status=='Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed'){

so, in test class you need to put task status other than completed (may be in progress) while inserting it. And update it by completed status.

Task task= new task(); task.Subject='Message Sent'; task.status='In Progress'; insert task;            
 task.status='Completed'; update task;

Try this hope this help to get your code covered.

All Answers

Himanshu Jasuja 9Himanshu Jasuja 9
Hi Srini,
Try this code
@isTest(SeeAllData=true)
public class TestemailonDuedate {
   public static testMethod void unitTest(){
     Test.startTest();
        EmailTemplate template = [SELECT id FROM EmailTemplate WHERE DeveloperName = 'Template_Name'];
            Task tsk=new Task();
            tsk.ActivityDate=System.Today();
            tsk.Subject='Test';
           tsk.Status='In Progress';
            tsk.Priority='Normal';
            Insert tsk;
        System.assertEquals(tsk.Subject,'Test');
            Test.stopTest();
  }
}

Hope this helps you.
SriniSrini
Hi Himanshu,

Thanks for your quick reply.But I havn't use any emai template .When we have run the test class we have got the error like "System.QueryException: List has more than 1 row for assignment to SObject".Please help me on this.
Thanks
Himanshu Jasuja 9Himanshu Jasuja 9
Hi Srini,
This error comes when your list does not have any records.
Try this sample code with your code 
Use the sample code given below to avoid the error :
 
List<Event> ev = [Select WhoId, Whatid, OwnerId from Event where WhoId = :t.Id];
 
if(ev.size() > 0)
{
   //your logic here
}
 
If the problems not solve yet so post your code here.I will look on it.

 
SriniSrini
Hi Himanshu.
My requirement is (If we assign a task to someone else, we can get an automated notice when the task is completed) For that we have created one trigger on Task Object Please find teh below trigger and based on that please help me the test class .

Please have look in to my trigger .

trigger TaskCompletedTrigger on Task (before update ) {
    Set<Id> ownerIds = new Set<Id>();
    for(Task tsk: Trigger.New){
      if(tsk.Status=='Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed'){
         ownerIds.add(tsk.CreatedById);      
        }        
    }
   Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :ownerIds]);
   
   List<Messaging.SingleEmailMessage> emailMsglist=new List<Messaging.SingleEmailMessage>();
    for(Task tsk : Trigger.New) {
       if(tsk.Status=='Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed'){
            User theUser = userMap.get(tsk.CreatedById);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    String[] toAddresses = new String[] {theUser.Email};
    mail.setToAddresses(toAddresses);    
    mail.setSubject('A task has been updated');     
    String template = 'Hello {0}, \nYour task has been Completed. Here are the details - \n\n';
    System.debug('========================'+template);

    template+= 'Subject -'+tsk.Subject+' \n';
    template+= 'Status - '+tsk.Status +' \n';       
    List<String> args = new List<String>();     
    args.add(theUser.Name);
    String formattedHtml = String.format(template, args);
    mail.setPlainTextBody(formattedHtml);
    emailMsglist.add(mail);    
            }     
        }
    Messaging.SendEmail(emailMsglist);
}
Himanshu Jasuja 9Himanshu Jasuja 9
Can you provide the test class code and the line number on which you are getting this error.?
SriniSrini
@isTest(SeeAllData=true) public class TaskCompletedTriggerTaskTest {
   public static testMethod void unitTest(){          
   Test.startTest();       EmailTemplate template = [SELECT id FROM EmailTemplate WHERE DeveloperName = 'Supp        ortSelfServiceNewLoginandPassword'];            
         Task task= new task(); task.Subject='Message Sent'; task.status='Completed'; insert task;              task.status='In Progress'; update task; Test.stopTest();                          
}
}

Thae above test class code is passed but code coverage it is showing 36%

not covered lines are 

ownerIds.add(tsk.CreatedById);   and

  User theUser = userMap.get(tsk.CreatedById);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

    String[] toAddresses = new String[] {theUser.Email};
    mail.setToAddresses(toAddresses);    
    mail.setSubject('A task has been updated');     
    String template = 'Hello {0}, \nYour task has been Completed. Here are the details - \n\n';
    System.debug('========================'+template);

    template+= 'Subject -'+tsk.Subject+' \n';
    template+= 'Status - '+tsk.Status +' \n';       
    List<String> args = new List<String>();     
    args.add(theUser.Name);
    String formattedHtml = String.format(template, args);
    mail.setPlainTextBody(formattedHtml);
    emailMsglist.add(mail);


the above code is not covered

Thanks







 
Himanshu Jasuja 9Himanshu Jasuja 9
In your code you are checking that the task current status should be completed and task old status should not be completed like below:

if(tsk.Status=='Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed'){

so, in test class you need to put task status other than completed (may be in progress) while inserting it. And update it by completed status.

Task task= new task(); task.Subject='Message Sent'; task.status='In Progress'; insert task;            
 task.status='Completed'; update task;

Try this hope this help to get your code covered.
This was selected as the best answer
SriniSrini
Hi Himanshu,

Wow. now it's coverd 100%

Thanks again!
Himanshu Jasuja 9Himanshu Jasuja 9
Please mark it as best answer if this solved your prob.
SriniSrini
Hi Himanshu,

I have one More issue on this 

my test execution is passed but  test execution says: Could not run tests on class 01p220000008ZFY(or whatever the Id is of the test I'm trying to run).Any ideas?
Thanks
Himanshu Jasuja 9Himanshu Jasuja 9
Hi srini,

try this link: https://success.salesforce.com/issues_view?id=a1p30000000T0FeAAK

https://success.salesforce.com/issues_view?id=a1p30000000T091AAC
SriniSrini

Hi Himanshu,

Thanks for your help!....

Himanshu Jasuja 9Himanshu Jasuja 9
Hi Srini,Why you changed the best anwser and assigned to you????
SriniSrini
Hi Himanshu,

Am Sorry for that unfortunately am unseleted that!.....
SriniSrini
Hi Himanshu,

As you know as of now test code is working fine,but yester day we  have added the two lines of code in the main trigger, but after adding the bit of code trigger is working fine, but that wolud effecting in the test class.Now code coverage is showing 32%. can you please help me on this.The one which we are added in the trrigger mentioned below

 template+= '\n\nFor more details, click the following link: \n\n';
 template+= URL.getSalesforceBaseUrl().toExternalForm() + '/' + tsk.Id;  

Below is the test calss:

@isTest(SeeAllData=true)
public class TaskEmailNotificationTest{
   static testMethod void Test(){    
 Test.startTest();
   EmailTemplate template = [SELECT id FROM EmailTemplate WHERE DeveloperName = 'ContactFollowUpSAMPLE'];            
   Task task= new task();
   task.Subject='Message Sent';
   task.status='In Progress';
   insert task;
   task.status='Completed';
   update task;
 Test.stopTest();                      
 }
}

Please help me on this.

Thanks in advance