Test class for custom Task component apex - Answers - Salesforce Trailblazer Community
Trailblazer Community
Ask Search:
Jonathan WolffJonathan Wolff 

Test class for custom Task component apex

Hello,

I build a custom task component that shows the subject and activity date of my tasks for the current and the next 2 days. I would like to bring the Component in my Salesforce live. Could you tell me how to build a test class for my Task apex.
This is my Apex code:

public with sharing class TaskController {
  
    @AuraEnabled
  public static List<Task> loadTasks(Id recordId){
      string userId = UserInfo.getUserId();
    return[SELECT Subject, ActivityDate FROM Task WHERE WhatId=:recordId And ActivityDate< TODAY 
           AND OwnerId=:userId AND Status !='Completed' ];
  }
    @AuraEnabled
  public static List<Task> loadTasks2(Id recordId){
      string userId = UserInfo.getUserId();
    return[SELECT Subject, ActivityDate FROM Task WHERE WhatId=:recordId And ActivityDate>= TODAY 
           AND ActivityDate  < Next_N_Days:1 AND OwnerId=:userId ];
  }
    @AuraEnabled
  public static List<Task> loadTasks3(Id recordId){
      string userId = UserInfo.getUserId();
      Date tomorrowDate = Date.today().addDays(1);
    Date dayAfterTomorrow = tomorrowDate.addDays(1);
    return[SELECT Subject, ActivityDate FROM Task WHERE WhatId=:recordId And ActivityDate>= :tomorrowDate AND ActivityDate  < :dayAfterTomorrow AND OwnerId=:userId ];
  }
   

    @AuraEnabled
  public static List<Task> loadTasks4(Id recordId){
      string userId = UserInfo.getUserId();
      Date tomorrowDate = Date.today().addDays(1);
      Date dayAfterTomorrow = tomorrowDate.addDays(1);
      Date twodaysAfterTomorrow = tomorrowDate.addDays(2);
    return[SELECT Subject, ActivityDate FROM Task WHERE WhatId=:recordId And ActivityDate>= :dayAfterTomorrow AND ActivityDate  < :twodaysAfterTomorrow AND OwnerId=:userId ];
  }
    
  
}
Best Answer chosen by Jonathan Wolff
Usman AliUsman Ali
Hi Jonathan,

Try below test class.
@isTest
private class TaskControllerTest 
{
    static testMethod void testMethod1() 
    {
        Account ac = new Account(Name = 'Test Account');
        insert ac ;

        Task tsk = new Task(Subject = 'Call', ActivityDate = Date.today().addDays(-1), Description = 'Test', WhatId = ac.Id );
        insert tsk ;

        TaskController.loadTasks(ac.Id);

        tsk.ActivityDate = Date.today().addDays(1);
        update tsk;
        TaskController.loadTasks2(ac.Id);


        tsk.ActivityDate = Date.today().addDays(2);
        update tsk;
        TaskController.loadTasks3(ac.Id);


        tsk.ActivityDate = Date.today().addDays(3);
        update tsk;
        TaskController.loadTasks4(ac.Id);

    }
}