+ Start a Discussion
Karthik YRCKarthik YRC 

Help me in modifying the below test class to increase code coverage

 public static void TaskTriggerUpdateAcc(List<Task> tsk){
      
          Map<Id,Date> accLastSignfInteractionMap = new Map<Id,Date>();
         Set<id> SetAccId = new set<id>();
       Map<id,Task> acctid = new Map<id,Task>([Select AccountId from Task where id in :tsk]) ;
       for(Task t: acctid.values()){
           SetAccId.add(t.accountid);
       }
      try {

          List < Task > taskList = new List < Task > ();
          if (SetAccId != null) {
              // taskList = [select id, Significant_Interactions__c, AccountId, ActivityDate, CreatedDate, LastSignificantDate__c from Task where Significant_Interactions__c = true and AccountId in :SetAccId order by ActivityDate DESC ];
              // System.debug('tasklist' + taskList);
              Date latestSignificantDate;
              for (Task t: [select id, Significant_Interactions__c, AccountId, ActivityDate, CreatedDate, LastSignificantDate__c from Task where Significant_Interactions__c = true and AccountId in : SetAccId order by ActivityDate DESC]) {
                  IF(t.Significant_Interactions__c == TRUE) {
                      IF(t.ActivityDate == null) {

                          IF(t.LastSignificantDate__c == null) {
                              t.LastSignificantDate__c = t.CreatedDate;
                              update t;
                              accLastSignfInteractionMap.put(t.AccountId, Date.valueOf(t.CreatedDate));
                          }
                          Else
                          if (t.LastSignificantDate__c < t.CreatedDate) {
                              t.LastSignificantDate__c = t.CreatedDate;
                              update t;
                              accLastSignfInteractionMap.put(t.AccountId, Date.valueOf(t.CreatedDate));

                          }
                          Else {
                              accLastSignfInteractionMap.put(t.AccountId, Date.valueOf(t.LastSignificantDate__c));
                          }
                      }
                      Else {
                          IF(t.LastSignificantDate__c == null) {
                              t.LastSignificantDate__c = t.ActivityDate;
                              update t;
                          }
                          Else
                          if (t.LastSignificantDate__c < t.ActivityDate) {
                              t.LastSignificantDate__c = t.ActivityDate;
                              update t;
                          }

                          latestSignificantDate = Date.valueof(t.LastSignificantDate__c);
                          IF(accLastSignfInteractionMap.get(t.AccountId) == null) {

                              accLastSignfInteractionMap.put(t.AccountId, Date.valueOf(latestSignificantDate));
                          } else if (accLastSignfInteractionMap.get(t.AccountId) < latestSignificantDate) {
                              accLastSignfInteractionMap.put(t.AccountId, latestSignificantDate);
                          }
                      }

                  }
              }
          }
          if (accLastSignfInteractionMap.size() > 0) {

    Map<Id, Account> accountMap = new Map<Id,Account>([select id,Last_Significant_Interaction__c from Account where id in: accLastSignfInteractionMap.keyset()]);

   
   for(Id accId : accLastSignfInteractionMap.keyset()){
       if(accountMap.get(accId)!=null){
           accountMap.get(accId).Last_Significant_Interaction__c = accLastSignfInteractionMap.get(accId);
       }
   
    }
    
update accountMap.values(); 
      }
      } catch (exception e) {
          ApplicationDebugLog.captureExceptionDetails(e);
          if (tsk.size() == 1)
              tsk[0].adderror('Request could not be processed.Please contact System Admin');
          else
              ApplicationDebugLog.captureExceptionDetails(e);
      }
  }

Below is the test class which i have written

@isTest(Seealldata=True)

public class  TestFS_Taskservicetest{ 

 /* Test data for Lead record to test Lead Contacted*/
    static Lead setupLeadsData(){
        Lead newLead = new Lead();
        newLead.LastName ='TestLead';
        newLead.status = 'New';
        newLead.Company ='Deloitte';
        newLead.LeadSource = 'Others';
        newLead.Phone = '(990) 009-3659';
        newLead.Primary_Phone_Type__c = 'Cell';
        newLead.Preferred_Contact_Method__c = 'Phone';
        //insert newlead;
        return newlead;
        
    }
    static Task setupTaskData(){
        Task taskRec = new Task();
        taskRec.OwnerId = UserInfo.getUserId();
        taskRec.Status = 'Completed';
        //taskRec.EndDateTime = System.Now().addHours(-3);
       taskRec.Significant_Interactions__c = true;
        taskRec.Description = 'This is test';
        taskRec.LastSignificantDate__c = System.Today()-1;
         return taskRec;
    }
    /* Test method to check Lead contacted logic */
    static testMethod void updateEventLeadstatusTest() {
        // TO DO: implement unit test
        Lead leadRec = setupLeadsData();
        insert leadRec;
        Task taskRec =  setupTaskData();
        taskRec.WhoId = leadRec.Id;
        
        Test.startTest();
        taskRec.FS_Lead_Contacted__c = true;
        insert taskRec;
        Test.stopTest();
        system.assertEquals(leadRec.Status , 'New');
    }
    /* Test method to check Lead contacted logic
       Is Due Date Changed flag should be reset after lead is marked marked as contactted */
    /*static testMethod void updateEventIsDueDateChangedTest() {
        // TO DO: implement unit test
        Lead leadRec = setupLeadsData();
        insert leadRec;
   }
    static Task setupTaskData(){
        Task taskRec = new Task();
        taskRec.OwnerId = UserInfo.getUserId();
        taskRec.Status = 'Completed';
        //taskRec.EndDateTime = System.Now().addHours(-3);
       taskRec.Significant_Interactions__c = true;
        taskRec.Description = 'This is test';
        taskRec.LastSignificantDate__c = System.Today()-1;
         return taskRec;
        Test.stopTest();
        system.assertEquals(eventRec.FS_Is_Due_Date_Changed__c , False);
    }*/
    
//private with sharing class FS_TaskServiceTest {

  /*static testmethod void insertTask() {

   User us = new User();
   Profile objProfile1 = new Profile();
   objProfile1 = [Select id, name from Profile where name = 'System Administrator' limit 1];
       us.FirstName = 'Test';
       us.LastName = 'User';
       us.Username = 'ankatariya@test.com';
       us.Email = 'ankatariya@deloitte.com';
       us.Alias = 'ankata';
       us.CommunityNickname = 'del';
       us.TimeZoneSidKey = '(GMT+5:30)Asia Standard Time(India/Kolkata)';
       us.LocaleSidKey = 'English(United States)';
       us.EmailEncodingKey = 'Unicode(UTF-8)';
       us.ProfileId = objProfile1.id;
       us.LanguageLocaleKey = 'English';
     
    insert us; */

 //Id userid = new Id([Select id from User where name = 'Anushka kataria']);
       
    
       
 static Testmethod void TestEventTriggerUpdateAcc() {      
    Account a = new Account(Name='Sample Account');
              insert a;
       Contact con = new Contact();
        con.FirstName = 'Test';
        con.LastName = 'Contact'; 
        con.AccountId = a.Id; // this assumes account is a required field on your contact records
        con.MailingCity = 'Bangalore'; // this is to validate the trigger
        con.MailingStreet = '331'; // this is to validate the trigger
        con.MailingState = 'CA'; // this is to validate the trigger
        con.MailingCountry = 'India'; // this is to validate the trigger
        con.MailingPostalCode = '56037'; // this is to validate the trigger
        con.Preferred_Contact_Method__c = 'Phone';
        con.Email = 'ank@deloitte.com';
        con.Phone = '(967) 567-8989';
        con.SPW_Phone_Type__c = 'Business';
      
    insert con;
Test.starttest();
    Task u = new Task();
        u.ownerId = '005E0000006ROAOIA4'; // you've now successfully created your test user, time to use it on your new task
        u.whoId = con.Id; // you've now successfully created your test contact, time to use it on your new task
        u.Subject = 'Run Test Trigger';
        u.Status = 'Not Started';
        u.Priority = 'Normal';
        u.Significant_Interactions__c = true;
        u.Description = 'This is test';
        u.LastSignificantDate__c = System.Today()-1;
    insert u;
    



    for (Task t : [SELECT Id, MailingCity__c, MailingStreet__c, MailingState__c, MailingCountry__c, MailingPostalCode__c FROM Task WHERE Id = :u.id]) {
        System.assertEquals('Bangalore', t.MailingCity__c); // asserts that your test worked properly
        System.assertEquals('331', t.MailingStreet__c); // asserts that your test worked properly
        System.assertEquals('CA', t.MailingState__c); // asserts that your test worked properly
        System.assertEquals('India', t.MailingCountry__c); // asserts that your test worked properly
        System.assertEquals('56037', t.MailingPostalCode__c); // asserts that your test worked properly
    }
test.stoptest();
}

public static Testmethod void TestTaskTriggerUpdateAcc() {
              Account a = new Account(Name='Sample Account');
              insert a;
              
              List<Task> tasks = new List<Task>();
            tasks.add(new Task( ActivityDate = Date.today().addDays(7),Subject='Sample Task',WhatId = a.Id,OwnerId = UserInfo.getUserId(),
            Status='In Progress'));
 
insert tasks;
}
}

 
pconpcon
The very first thing I would do is to drop the SeeAllData from your test class.  Then, you'll want to create a test that generates your task data in such a way that meets each of your if statements in your trigger.  I would recommend reading over this

http://blog.deadlypenguin.com/blog/testing/strategies/