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
amritamrit 

Code coverage in Task trigger

Hi,

 

Here im created a trigger and test class.Currently im having 44% code coverage.How to achieve 100% for this trigger.

trigger MailTask on Task (after insert,after update)
{
    set<String> setownerIds = new set<String>();
    Set<ID> TaskId = new Set<Id>();
     if((Trigger.isUpdate)){
    for(Task TaskObj : Trigger.New)
    {
        TaskId.add(TaskObj.Id);       
    }
    Task[] TaskList = [Select Id,Owner.Name,CreatedByID,OwnerId,Owner.Email,Subject,ActivityDate,Priority,Status,Description,What.Type,What.Name,Who.type,Who.Name from Task where Id in : TaskId];
    system.debug('Tasklist'+TaskList);
    Map<Id,Account> AccountMap ;
    Map<Id,Lead> LeadMap ;
    Map<Id,Opportunity> OpportunityMap;
    Map<Id,Contact> ContactMap ;
  
    Set<Id> AccountId = new Set<Id>();
    Set<Id> LeadId = new Set<Id>();
    Set<Id> OpportunityId = new Set<Id>();
    Set<Id> ContactId = new Set<Id>();
   
    //if(Trigger.isUpdate && Trigger.isBefore)
   
    for(Task TaskObj : TaskList)
    {
        
        if(TaskObj.Who.Type == 'Lead')
        {
            LeadId.add(TaskObj.whoId);
        }
        if(TaskObj.who.Type == 'Contact')
        {
            ContactId.add(TaskObj.WhoId);
        }
        if(TaskObj.what.Type == 'Account')
        {
            AccountId.add(TaskObj.WhatId);
        }
        if(TaskObj.what.Type == 'Opportunity')
        {
            OpportunityId.add(TaskObj.WhatId);
        }
       
        
    }
     
    AccountMap =  new Map<Id,Account>([Select Id,Name,Owner.Email from Account where Id in : AccountId ]);
    LeadMap = new Map<Id,Lead>([Select Id,Name,Owner.Email from Lead where Id in : LeadId ]);
    OpportunityMap  = new Map<Id,Opportunity>( [Select Id,Name,Owner.Email from Opportunity where Id in : OpportunityId ]);
    system.debug('opportunitymap!!!!!!!!!!!!!'+OpportunityMap);
    ContactMap = new Map<Id,Contact>([Select Id,Owner.Email,Name from Contact where Id in : ContactId ]);

    
    for(Task TskObj : TaskList)
    {
     
    if(TskObj.OwnerId != TskObj.CreatedByID){
       String[] toAddresses ;
        String forName = '';
        if(TskObj.who.Type == 'Contact')
        {
           toAddresses = new String[] {(ContactMap.get(TskObj.WhoId).Owner.Email)};
            forName = TskObj.who.Name;
        }
        if(TskObj.Who.Type == 'Lead')
        {
           toAddresses = new String[] {(LeadMap.get(TskObj.WhoId).Owner.Email)};
            forName = TskObj.who.Name;
        }
        if(TskObj.what.Type == 'Account')
        {
             toAddresses = new String[] {(AccountMap.get(TskObj.WhatId).Owner.Email)};
             forName = TskObj.what.Name;
        }
        if(TskObj.what.Type == 'Opportunity')
        {
         toAddresses = new String[] {(OpportunityMap.get(TskObj.WhatId).Owner.Email)};
        system.debug('Address'+ toAddresses);
        
         forName = TskObj.what.Name;
          system.debug('name'+forName);
        }
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        system.debug('ToAddress'+toAddresses);
        mail.setToAddresses(toAddresses);
        system.debug('Mail '+mail);
        mail.setSubject('A task assigned by you has Completed');  
        
         system.debug('Mail subject'+mail);  // Set the subject
        String template = 'Hello, \nYour assigned task has Completed. Here are the details - \n\n';
        template+= 'Subject - {0}\n';
        template+= 'Related to - {1}\n';
        template+= 'Due Date - {2}\n';
        template+= 'Priority - {3}\n';
        template+= 'Comments - {4}\n';
        
        String duedate = '';
        if (TskObj.ActivityDate==null)
            duedate = '';
        else
            duedate = TskObj.ActivityDate.format();
            system.debug('Duedate'+duedate);
        List<String> args = new List<String>();
         
        args.add(TskObj.Subject);
        
        args.add(forName);
      
        args.add(duedate);
        args.add(TskObj.Priority);
        args.add(TskObj.Description);
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   }  
      
  }

}
}

 Test class

@isTest
public class testemailalert
{
 static testmethod void testemailalertmethod()
 {
       
       Messaging.Singleemailmessage testEmail;
        List<Messaging.Sendemailresult> testEmailResults;
        Opportunity testOpp = new Opportunity( Name ='TestOpp', StageName ='Prospecting', CloseDate = System.today());
        insert testOpp;
        Account acc=new Account(Name='Testaccount');
        insert acc;
        Lead ld=new Lead(LastName='testlead',Company=acc.Id,Status='Open-Not Contacted');
        insert ld;
        Contact cd=new Contact(LastName='testcontact',Email='amritaaravind@gmail.com');
        insert cd;
       // List<Task> taskList = new List<Task> ();
      //  taskList.add(new Task(Subject='test',Priority='Medium',Status='Completed',WhatId=acc.id,WhoId=cd.id,ActivityDate=System.today()));     
       // insert taskList;
          test.startTest(); 
       List<Task> taskList = new List<Task> ();
       Task t = new Task();
      
        t.OwnerId = UserInfo.getUserId();
        system.debug('User----------------'+t.OwnerId );
        t.Subject='Send Out Notice To Vacate';
        t.Status='Not Started';
        t.Priority='Normal';
        t.WhatId=testOpp.Id;
        t.WhoId=cd.id;
        insert t;
     
        t.Priority='High';
        t.Status='Completed';
        update t;     
        taskList.add(t);
        Task testTask2 = new Task (OwnerId = UserInfo.getUserId(),WhatId = acc.Id,WhoId = cd.Id,Subject = 'Other', Status ='In Progress',ActivityDate=System.today());
        insert testTask2;
        Task testTask3 = new Task (OwnerId = UserInfo.getUserId(),WhoId = ld.Id,Subject = 'Other', Status ='In Progress',ActivityDate=System.today());
        insert testTask3;
         Task testTask4 = new Task (OwnerId = UserInfo.getUserId(),WhoId = cd.Id,Subject = 'Other', Status ='In Progress',ActivityDate=System.today());
        insert testTask4;
        testTask4.Status = 'Completed';
        update testTask4;
       
        Task edTask2 = [Select t.WhatId, t.Subject, t.Status From Task t where t.Id=:testTask2.Id];
        edTask2.Status = 'Completed';
        update edTask2;
        taskList.add(edTask2);
        Task edTask3 = [Select t.WhoId, t.Subject, t.Status From Task t where t.Id=:testTask3.Id];
        edTask3.Status = 'Completed';
        update edTask3;
        taskList.add(edTask3);
        String[] toAddresses ;
        String forName = '';
        if(testTask4.who.Type == 'Contact')
           {
            toAddresses = new String[] {'amritaaravind@gmail.com'};
            }
            testEmail.setToAddresses(toAddresses);
         test.stopTest();
      
 
 }
 
 
 }

 This is related to task.Im not able to get coverage for  the address in Messaging.sendemailmessage..Please suggest me any methods to get more coverage fo this

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
Hong_YanHong_Yan

Is the section of the code that's not being covered after this part?

 if(TskObj.OwnerId != TskObj.CreatedByID){

 

Everything in this if statement will only run if the ownerId is different from the CreatedById

 

However, you always set the OwnerId to the current user which is the same as the createdbyid

 

Try setting the owner to another user on your tasks.

 

All Answers

Hong_YanHong_Yan

Is the section of the code that's not being covered after this part?

 if(TskObj.OwnerId != TskObj.CreatedByID){

 

Everything in this if statement will only run if the ownerId is different from the CreatedById

 

However, you always set the OwnerId to the current user which is the same as the createdbyid

 

Try setting the owner to another user on your tasks.

 

This was selected as the best answer
amritamrit

Hi,

 

Thanks for you reply.Yes you are correct. It is covering 92% now.But when im trying to deploy the code to production and we dont have that specific user id.Then again it will throw an error.Without using user id  how we can test this