+ Start a Discussion
Nagarjuna Reddy.PNagarjuna Reddy.P 

test class for trigger updates field on account

Hi All,
             Could any one please provide test class for the following trigger that updates field on account.

apexclass...

  public with sharing class CountofTasks{
    public static void updateAcc(List<Task> tasks){
        set<id> accids = new set<id>();
        for(Task t:tasks){
            if(t.whatid!=null){
                accids.add(t.whatid);
            }
        }
        List<Account> accounts = [select id,Task_Count__c from Account where id in:accids];
       integer count = [select count() from Task where whatid in:accids];
        if(count >0){
            for(Account a:accounts){
                 a.Task_Count__c = count ;
            }
                   } 
              update accounts;
    }
Trigger...

  trigger ExampleTrigger on Task (after insert,after delete) {
    if(Trigger.isInsert && Trigger.isAfter){
        CountofTasks.updateAcc(Trigger.New);
  }
}
Thanks in Advance....
Rounak SharmaRounak Sharma
hello Nagarjuna,
You can refer https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_triggers
Please let me know if still having doubt
thanks
Nagarjuna Reddy.PNagarjuna Reddy.P
Thank you Rounak for your quick reply,I will go through this link.
Deepali KulshresthaDeepali Kulshrestha
Hi Nagarjuna

Please use following code it will cover 100% of your code.
@isTest
public class CountofTasks_Test {
    @isTest
    public static void testAccount(){
        try{   
            Account acc = new Account();
            acc.name = 'Test';
            acc.Phone = '999434837';
            insert acc;  
            

            Task tsk1 = new Task();
            tsk1.WhatId = acc.Id; 
            tsk1.Subject = 'Email';
            tsk1.ActivityDate = date.today(); 
            tsk1.Status = 'Completed';
            insert tsk1; 
            
            Test.startTest();
            acc.Name = 'testAcc';
            Update acc;
            Test.stopTest();

        }
        Catch(Exception e){
            
            System.debug('Error-----'+e.getMessage() + 'At line number>>>>>>'+e.getLineNumber());
        }
    }  
}

++++++++++++++++++++++++++++++++Trigger+++++++++++++++++++++++++++++++++
 trigger ExampleTrigger on Task (after insert,after delete) {
    if(Trigger.isInsert && Trigger.isAfter){
        CountofTasks.updateAcc(Trigger.New);
  }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com