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
AviKesariAviKesari 

need help - test class

Hi all,

I need help on test class, this is my class:

When creating a task of type (Phone Call or Last Face to Face) from contact,need to update the account fields

I have a trigger:
trigger TaskTrigger on Task (after delete, after insert, after undelete, after update, before delete, before insert, before update) {
    
    TaskTriggerHandler handler = new TaskTriggerHandler (Trigger.isExecuting, Trigger.size);
    //After Update
     if(Trigger.isUpdate && Trigger.isAfter){
         handler.OnAfterUpdate(Trigger.new,Trigger.oldMap);
          
   }
 }

TriggerHandler class:

public with sharing class TaskTriggerHandler {
    
    private boolean trigger_isExecuting = false;
    private integer batchSize = 0;
    
    public TaskTriggerHandler ( boolean isExecuting, integer size){
        trigger_isExecuting = isExecuting;
        batchSize = size;        
    }

    public void OnAfterUpdate(List<Task> Tklist, Map<id,Task> OldMaplst){
        //EXECUTE AFTER UPDATE LOGIC
        //first condition is to check the record type then 
         Set<ID> tid = new Set<ID>();
         list<Account> acclst = new list<Account>();
        
        for(Task tk:Tklist){
        if(tk.Whoid!=null && tk.WhoId.getSObjectType().getDescribe().getName()=='Contact'){
         tid.add(tk.whoid);
            }
          }
        List<Contact> con = new List<Contact>();
        con=[select id,accountid from Contact where id =:tid];
        Map<id,account>Lstacc=new Map<id,account>();
        if(!con.isEmpty()){
            account acc;
            for(Task tk:[select id,LastModifiedBy.name,type,LastModifiedDate from task where id in :Tklist]){
                DateTime dt = tk.LastModifiedDate;
                Date myDate = date.newinstance(dt.year(), dt.month(), dt.day());
                acc=new account(id=con[0].accountid);
                    if(tk.type=='Face 2 Face Meeting'){
                        acc.Last_Face_to_Face_Activity__c= myDate;
                        acc.Last_Visited_By__c =tk.LastModifiedBy.name;
                        
                    }
                    else if(tk.type=='Phone Call'){
                     acc.Last_Call_Activity__c =  myDate;
                    }
                     Lstacc.put(acc.id,acc);
        }
                if(!Lstacc.isEmpty())
                    Update Lstacc.values();

    }
  }
}
Best Answer chosen by AviKesari
Raj VakatiRaj Vakati
Change yout test class as below 
 
@isTest
public class TaskTriggerHandlerTest 
{
static testMethod void testStandardUserwithTask() 
{
    Profile standardProf = [select id from profile where name='Standard 
                             User'];
    User su = new User(alias = 'standt',         
    email='standarduser@asdasdasdasdasd.com',emailencodingkey='UTF- 
                                 8',FirstName='task',
        lastname='testing',languagelocalekey='en_US',localesidkey='en_US',profileid = standardProf.Id,
                       timezonesidkey='America/Los_Angeles',username='standarduser@asdasdasdasdasdasd.com');
    System.runAs(su) 
    {
        Account a = new Account(name='Testtask');
        insert a;
		
//insert contact her 

Contact con = new Contact(LastName ='Demo' ,AccountId =a.Id , Email='test@gmail.com');
insert con ; 

        List<Task> tasks = new List<Task>{};
            for(Integer i = 0; i < 5; i++) 
        {
            Task t = new Task(Subject='Donni'+i,Status='New',Priority='Normal',CallType='Outbound' ,whoid = a.Id );
            tasks.add(t);
        }
        test.startTest();
        insert tasks;
        test.stopTest();
        
        try 
        {
            delete tasks;
        } 
        catch (Exception e) 
        {
           
        }
       
    }

}
   static testMethod void testAdminUserwithTask() {

    // Next make sure that a System Admin *can* delete an attachment
    Profile adminProf = [select id from profile where name='System Administrator']; 
        User au = new User(alias = 'Admint', email='AdminUser@asdahsdjkhkjashdjasd.com',emailencodingkey='UTF-8',FirstName='Admin',
                       lastname='task',languagelocalekey='en_US',localesidkey='en_US',profileid = adminProf.Id,
                       timezonesidkey='America/Los_Angeles',username='AdminUser@asdahsdjkhkjashdjasd.com');
    // Switch current user to System Admin user
    System.runAs(au) {

        // Create test data (a new Account with an Attachment)
        Account a = new Account(Name='Testtasking');
        insert a;
		Contact con = new Contact(LastName='Test',AccountId = a.Id , FirstName='asdasd',Email='asdasd@adsasd.com') ;
		insert con ; 
        List<Task> tasks = new List<Task>{};
            for(Integer i = 0; i < 200; i++) 
        {
            Task t = new Task(Subject='Donni'+i,Status='New',Priority='Normal',CallType='Outbound' ,whoId =con.Id );
            tasks.add(t);
        }
        test.startTest();
        insert tasks;
        test.stopTest();
       
        try {
            delete tasks;
        } catch (Exception e) {
            
        }
       
    }
}

}

 

All Answers

Britto Fernandez 2Britto Fernandez 2
Hi AviKerari,

You may want to put try....catch in your code

For test class/method, one of option is 
- create a input file with multiple records of task and upload to static resource.
- insert record from static resource and it will fire your trigger and execute other apex class
- create another input fiel with account details and upload to static resource
- compare the list from 3rd step and query for records of account and decide fail/success.

Give it a try and intimate if you were able to progress....
AviKesariAviKesari
Thanks for the reply Britto, Please can you give an example of code that will be a great help
Raj VakatiRaj Vakati
try this
@isTest
public class TaskTriggerHandlerTest 
{
static testMethod void testStandardUserwithTask() 
{
    Profile standardProf = [select id from profile where name='Standard 
                             User'];
    User su = new User(alias = 'standt',         
    email='standarduser@asdasdasdasdasd.com',emailencodingkey='UTF- 
                                 8',FirstName='task',
        lastname='testing',languagelocalekey='en_US',localesidkey='en_US',profileid = standardProf.Id,
                       timezonesidkey='America/Los_Angeles',username='standarduser@asdasdasdasdasdasd.com');
    System.runAs(su) 
    {
        Account a = new Account(name='Testtask');
        insert a;
		
        List<Task> tasks = new List<Task>{};
            for(Integer i = 0; i < 5; i++) 
        {
            Task t = new Task(Subject='Donni'+i,Status='New',Priority='Normal',CallType='Outbound' ,whoid = a.Id );
            tasks.add(t);
        }
        test.startTest();
        insert tasks;
        test.stopTest();
        
        try 
        {
            delete tasks;
        } 
        catch (Exception e) 
        {
           
        }
       
    }

}
   static testMethod void testAdminUserwithTask() {

    // Next make sure that a System Admin *can* delete an attachment
    Profile adminProf = [select id from profile where name='System Administrator']; 
        User au = new User(alias = 'Admint', email='AdminUser@asdahsdjkhkjashdjasd.com',emailencodingkey='UTF-8',FirstName='Admin',
                       lastname='task',languagelocalekey='en_US',localesidkey='en_US',profileid = adminProf.Id,
                       timezonesidkey='America/Los_Angeles',username='AdminUser@asdahsdjkhkjashdjasd.com');
    // Switch current user to System Admin user
    System.runAs(au) {

        // Create test data (a new Account with an Attachment)
        Account a = new Account(Name='Testtasking');
        insert a;
		Contact con = new Contact(LastName='Test',FirstName='asdasd',Email='asdasd@adsasd.com') ;
		insert con ; 
        List<Task> tasks = new List<Task>{};
            for(Integer i = 0; i < 200; i++) 
        {
            Task t = new Task(Subject='Donni'+i,Status='New',Priority='Normal',CallType='Outbound' ,whoId =con.Id );
            tasks.add(t);
        }
        test.startTest();
        insert tasks;
        test.stopTest();
       
        try {
            delete tasks;
        } catch (Exception e) {
            
        }
       
    }
}

}

 
AviKesariAviKesari
I will give try and let you know, thanks Raj
Raj VakatiRaj Vakati
wokring ?
AviKesariAviKesari
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TaskTrigger: execution of AfterUpdate

caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []

Class.TaskTriggerHandler.OnAfterUpdate: line 59, column 1
Trigger.TaskTrigger: line 26, column 1: []

I'm getting the above error
Raj VakatiRaj Vakati
Looks like you have't added id while updating the records . ISSING_ARGUMENT, Id not specified in an update call
 

please check in code 
AviKesariAviKesari
I'm updating the account fields, so you mean account IDs in the triggerhandler class?
Raj VakatiRaj Vakati
yes .. here from this link   account acc

 
account acc;
            for(Task tk:[select id,LastModifiedBy.name,type,LastModifiedDate from task where id in :Tklist]){
                DateTime dt = tk.LastModifiedDate;
                Date myDate = date.newinstance(dt.year(), dt.month(), dt.day());
                acc=new account(id=con[0].accountid);
                    if(tk.type=='Face 2 Face Meeting'){
acc.Id = 'YOUR ACCOUNID' ;
                        acc.Last_Face_to_Face_Activity__c= myDate;
                        acc.Last_Visited_By__c =tk.LastModifiedBy.name;
                        
                    }
                    else if(tk.type=='Phone Call'){
                     acc.Last_Call_Activity__c =  myDate;
                    }
                     Lstacc.put(acc.id,acc);
        }
                if(!Lstacc.isEmpty())
                    Update Lstacc.values();

    }

 
AviKesariAviKesari
account acc;
            for(Task tk:[select id,LastModifiedBy.name,type,LastModifiedDate from task where id in :Tklist]){
                DateTime dt = tk.LastModifiedDate;
                Date myDate = date.newinstance(dt.year(), dt.month(), dt.day());
               // acc=new account(id=con[0].accountid);
                    if(tk.type=='Face 2 Face Meeting'){
                     acc.Id = con[0].accountid; //updated HERE
                        acc.Last_Face_to_Face_Activity__c= myDate;
                        acc.Last_Visited_By__c =tk.LastModifiedBy.name;
                        
                    }
                    else if(tk.type=='Phone Call'){
                     acc.Id = con[0].accountid; //updated HERE 
                     acc.Last_Call_Activity__c =  myDate;
                    }
                     Lstacc.put(acc.id,acc);
        }
                if(!Lstacc.isEmpty())
                    Update Lstacc.values();

    }

But I'm getting a different error:

caused by: System.NullPointerException: Attempt to de-reference a null object

 
Raj VakatiRaj Vakati
Change yout test class as below 
 
@isTest
public class TaskTriggerHandlerTest 
{
static testMethod void testStandardUserwithTask() 
{
    Profile standardProf = [select id from profile where name='Standard 
                             User'];
    User su = new User(alias = 'standt',         
    email='standarduser@asdasdasdasdasd.com',emailencodingkey='UTF- 
                                 8',FirstName='task',
        lastname='testing',languagelocalekey='en_US',localesidkey='en_US',profileid = standardProf.Id,
                       timezonesidkey='America/Los_Angeles',username='standarduser@asdasdasdasdasdasd.com');
    System.runAs(su) 
    {
        Account a = new Account(name='Testtask');
        insert a;
		
//insert contact her 

Contact con = new Contact(LastName ='Demo' ,AccountId =a.Id , Email='test@gmail.com');
insert con ; 

        List<Task> tasks = new List<Task>{};
            for(Integer i = 0; i < 5; i++) 
        {
            Task t = new Task(Subject='Donni'+i,Status='New',Priority='Normal',CallType='Outbound' ,whoid = a.Id );
            tasks.add(t);
        }
        test.startTest();
        insert tasks;
        test.stopTest();
        
        try 
        {
            delete tasks;
        } 
        catch (Exception e) 
        {
           
        }
       
    }

}
   static testMethod void testAdminUserwithTask() {

    // Next make sure that a System Admin *can* delete an attachment
    Profile adminProf = [select id from profile where name='System Administrator']; 
        User au = new User(alias = 'Admint', email='AdminUser@asdahsdjkhkjashdjasd.com',emailencodingkey='UTF-8',FirstName='Admin',
                       lastname='task',languagelocalekey='en_US',localesidkey='en_US',profileid = adminProf.Id,
                       timezonesidkey='America/Los_Angeles',username='AdminUser@asdahsdjkhkjashdjasd.com');
    // Switch current user to System Admin user
    System.runAs(au) {

        // Create test data (a new Account with an Attachment)
        Account a = new Account(Name='Testtasking');
        insert a;
		Contact con = new Contact(LastName='Test',AccountId = a.Id , FirstName='asdasd',Email='asdasd@adsasd.com') ;
		insert con ; 
        List<Task> tasks = new List<Task>{};
            for(Integer i = 0; i < 200; i++) 
        {
            Task t = new Task(Subject='Donni'+i,Status='New',Priority='Normal',CallType='Outbound' ,whoId =con.Id );
            tasks.add(t);
        }
        test.startTest();
        insert tasks;
        test.stopTest();
       
        try {
            delete tasks;
        } catch (Exception e) {
            
        }
       
    }
}

}

 
This was selected as the best answer
AviKesariAviKesari
no luck, I have updated the test class, still the same null reference error.
AviKesariAviKesari
I have updated the code to :
whatid is account id and whoid is contact id..is this causing an issue? 


  List<Task> tasks = new List<Task>{};
            for(Integer i = 0; i < 5; i++) 
        {
            Task t = new Task(Subject='Donni'+i,Status='New',Priority='Normal',Type='Face 2 Face Meeting' ,whatid = a.Id, Whoid = c.Id );
            tasks.add(t);
        }
AviKesariAviKesari
update of account in the end helped to fix the issue. Thanks raj!