+ Start a Discussion
Jon RodigerJon Rodiger 

Help needed with Task Completion trigger and Test Class

I'm trying to write a trigger that schedules a new task for the same user that completed a specified task. This is my trigger so far and I am trying to test it, but I am not sure how to assign a completed task to a user and then check if a new task was created for that user.
trigger finTask on Task (after insert, after update) {
    // Iterate through all tasks
    for(Task t : Trigger.new){
        // Schedule follow up task for completed tasks
        if(t.Status == 'Completed'){
            if(t.Subject == 'Send Initial Email'){
                Task newTask = new Task(Subject = 'Make Initial Phone Call', IsReminderSet = True, ReminderDateTime = System.now()+1, WhoId = t.WhoId, ownerId = t.ownerId);
                insert newTask;
            } else if(t.Subject == 'Make Initial Phone Call'){
                //scheduleEmail2(t.OwnerId);
            } else if(t.Subject == 'Send Email #2'){
                //schedulePhone2(t.OwnerId);
            }
        }
    }
}
This is my test class so far
@isTest
private class TestTaskScheduler {
    public static testMethod void validateScheduler(){
    
    Test.startTest();
    
    String userId = UserInfo.getUserId();

    Task task = new Task();
        task.OwnerId = userId;
        task.Subject = 'Send Initial Email';
        task.priority= 'Normal';
        task.status = 'Completed';
        task.description = 'Testing';
        task.ActivityDate = system.now();
        insert task;
    Test.stopTest(); 
    }
}
Any help would be greatly appreciated. Thanks!
 
Best Answer chosen by Jon Rodiger
GauravGargGauravGarg
Hi Jon,

Task trigger works fine as per your requirement. Whenever a task is updated to "completed" status, then new task will be assigned to the user who has completed previous task. 
Please use below code for test code coverage.
@isTest
private class TestTaskScheduler {
    public static testMethod void validateScheduler(){
    
    System.Test.startTest();
    String userId = UserInfo.getUserId();
	List<Task> taskList = new List<Task>();
        for(integer i = 0; i < 5; i++){
            Task t = new Task();
            t.OwnerId = userId;
            t.Subject = 'Send Initial Email';
            t.priority= 'Normal';
            t.status = 'Completed';
            t.description = 'Testing';
            t.ActivityDate = system.now().Date();
            taskList.add(t);
        }
        taskList[1].Subject = 'Make Initial Phone Call';
        taskList[2].Subject = 'Send Email #2';
        insert taskList;
    System.Test.stopTest(); 
    }
}

Hope this will helps you, let me know if you need any further assitance on this. 

Thanks,
Gaurav
Email: gauravgarg.nmims@gmail.com
Skype: gaurav62990