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
SFHelpMePleaseSFHelpMePlease 

cannot get enough test coverage

Hello,

I created a test class for the below apex code but cannot get coverage when calling the AccountConversationUpdate  execute() (It is red in the console).  Could you explain what I need to do. The code works and gives me the results I need.    Thanks!

global class AccountUpdate implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {

        List<AggregateResult> acctIdList= [SELECT AccountId From Task where subject like 'Re%' group by AccountId];
        Set<Id> ids = new Set<Id>();
        for (AggregateResult ar : acctIdList) {
          ids.add(((Id)ar.get('AccountId')));
          System.debug('Account to update ' + (Id)ar.get('AccountId'));
       }
        String query = 'SELECT  Id, Name  From Account where Id in :ids';
        return Database.getQueryLocator(query);
    }

     
    global void execute(Database.BatchableContext BC, List<Account> acctList) {
        
        integer noOfDays = 0;
        integer 90Days =0;
         
        for(Account acc : acctList)
        {
            List<Task> taskList = [SELECT  Id, Subject, CreatedDate, AccountId, TaskSubtype FROM Task where subject like 'Re%' and AccountId = :acc.Id];
            for(Task t : taskList)
            {
                noOfDays = Date.today().daysBetween(t.CreatedDate.Date())*-1;
                if (noOfDays > 90)
                    90Days = 90Days + 1;
            }
            acc.90_Days__c  = 90Days ;
            update acctList;
        }
    }   
     
    global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations
  }
}



@isTest
public class AccountUpdateTest 
{
    static testMethod void testMethod1() 
    {
        List<Account> lstAcct = new List<Account>();
        List<Task> lstTask = new List<Task>();
        for(Integer i=0 ;i <200;i++)
        {
            Account acc = new Account();
            acc.Name ='Name'+i;
            lstAcct.add(acc);

            Task tsk = new Task();
            tsk.Subject = 'Re ' + i;
            tsk.TaskSubType = 'Call';
            tsk.WhatId = acc.Id;
            lstTask.add(tsk);

        }
        insert lstAcct ;
        insert lstTask ;

        Test.startTest();
            AccountConversationUpdate  obj = new AccountConversationUpdate();
            DataBase.executeBatch(obj); 
        Test.stopTest();
    }
}
SFHelpMePleaseSFHelpMePlease
I see the problem, account was not inserted yet so there was no id to assign to the task.WhatId.
I have fixed by inserting the accounts first then adding a task.

Thanks!