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
Sloan ManaSloan Mana 

Help with Testing a Task Trigger that Updates Task Record Type

Hi there, I am very new to Apex coding, and I feel a bit out of my league here, tbh.  I was hoping someone might be able to help me create a Test Class for a Trigger I've created...

I created a trigger on tasks that updates the record type if the task subject contains "Statement Reminder" or "Collection Letter".  Unfortunately, I cannot just use a SF workflow or process to do this because this sort of task is created when a user sends an email out which I guess is a "soft" process that does not activate workflows.  I've copied the code for my trigger below, and it seems to work, but I'm having trouble creating the test class for it.  I'd really appreciate anyone's help!

trigger CollectionTaskRecordType on Task (before insert, before update) {
    for(task t:Trigger.new){
        if(t.Type == 'Email' && t.Subject.contains('Statement Reminder') || t.Type== 'Email' && t.Subject.contains('Collection Letter')){
            (t.RecordTypeId = '01236000000yN92AAE');
        }
    }
}
Shiva RajendranShiva Rajendran
Hi Sian,

Please use the below code
@isTest
                private class TaskTriggerTestClass
                {
                     public static testMethod void testTaskTriggerUpdate()
                  {
                    User u = [select name,Id,User_Region_c,profileId=:[select Id from profile where name='system administrator'].Id  limit 1];
                    system.runAs(u)
                   {
                //during task creation give some other recordtypeid other than '01236000000yN92AAE' as default //value
                               List<Task> tasksList=new List<Task>();
                                Task tt= new task(Type ='Email',Subject= 'testaccount');
                                tasksList.add(tt);
 
                                        Task tt1= new task(Type ='Email',Subject= 'testaccount');
                                tasksList.add(tt1);

                            Task tt2= new task(Type ='Email',Subject= 'Collection Letter');
                                tasksList.add(tt2);


                            Task tt2= new task(Type ='somethingelse',Subject= 'Collection Letter');
                                tasksList.add(tt2);
                             insert tasksList;

                                List<Task> AllTasks= [select id,type,subject,recordtypeid from task where id in :tasksList];

RecordType  r=[select id from RecordType  where id='01236000000yN92AAE'];
System.assertEquals(AllTasks.get(0).recordtypeid, r.id); 

System.assertEquals(AllTasks.get(1).recordtypeid,r.id); 

System.assertNotEquals(AllTasks.get(2).recordtypeid, r.id); 


   Task updateTask= tasksList.get(2);
   updateTask.Type='Email';
update updateTask;

   System.assertEquals(updateTask.recordtypeid, r.id);

                   }
                }
           }
 

​

Not a verified code.May have code issue's since i wrote in the fly.
Let me know if you faced any issue or need further help.

Thanks and Regards,
Shiva RV
Amit Chaudhary 8Amit Chaudhary 8
Hi,

Dnt use hard coding in trigger. Try to update your code like below
trigger CollectionTaskRecordType on Task (before insert, before update) {

	Id taskRecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();
    for(task t:Trigger.new){
        if(t.Type == 'Email' && t.Subject.contains('Statement Reminder') || t.Type== 'Email' && t.Subject.contains('Collection Letter')){
            t.RecordTypeId = taskRecordTypeId;
        }
    }
}

Try test class like below
@isTest
private class TaskTriggerTestClass
{
	public static testMethod void testTaskTriggerUpdate()
	{

			Account acc = new Account();
			acc.name ='Test';
			insert acc;

			Id taskRecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();			
			
			Task tt= new task(Type ='Email',Subject= 'Statement Reminder',ActivityDate = Date.today().addDays(7), WhatId = acc.Id,Status='In Progress');
			insert tt;
			List<Task> AllTasks= [select id,recordtypeid from task where id = :tt.id ];
			System.assert( AllTasks.size() > 0 );
			System.assert( AllTasks[0].recordtypeid == taskRecordTypeId );
			
		}
	}
}


​


Let us know if this will help you

 
Sloan ManaSloan Mana
Thank you both tremendously for your replies!

Shiva, I tried created the test class you suggested, but it keeps giving me a problem on line 6 for "unexpected token:  = " - any ideas?

Amit, I also tried creating and running your suggestion, but it failed because I have a validation in place that requires the Who Id field to be filled in if the Task Type = Face-to-Face Meeting.  Should I just deactivate this validation rule during the test period then reactivate once deployed?  Also, and I apologize if this is a silly question here, but how will the Trigger know which record type id to assign if I do not hard code it?
Amit Chaudhary 8Amit Chaudhary 8
Can you please post your validation rule here so that we can update test class accordingly
Sloan ManaSloan Mana
Tasks with a Face to Face Meeting type require a Contact or Lead Name.

TEXT (Type)  = "Face to Face Meeting" && ISBLANK(WhoId)
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class
@isTest
private class TaskTriggerTestClass
{
	public static testMethod void testTaskTriggerUpdate()
	{

			Account acc = new Account();
			acc.name ='Test';
			insert acc;

			Contact cont = new Contact();
			cont.FirstName ='Test';
			cont.LastName ='Test';
			cont.accountid = acc.id;
			insert cont;
			
			
			Id taskRecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();			
			
			Task tt= new task(Type ='Email',Subject= 'Statement Reminder',ActivityDate = Date.today().addDays(7), WhatId = acc.Id,Status='In Progress' ,whoid = cont.id);
			insert tt;
			List<Task> AllTasks= [select id,recordtypeid from task where id = :tt.id ];
			System.assert( AllTasks.size() > 0 );
			System.assert( AllTasks[0].recordtypeid == taskRecordTypeId );
			
		}
	}
}


​

Let us know if this will help you
 
Sloan ManaSloan Mana
Darn okay so two more problems occured... the first is related to another validation rule which is on our Accounts (listed below).
The second issue is due to another AccountTrigger we have in place - the error referenced Line 54 on the Class and Line 6 on the Trigger (referenced lines are in bold and underlined below).

Any ideas? Again, I greatly appreciate your help!!

Account Validation Rule:
Customer Address is a required field on Accounts.  Please enter the address information before saving the record.

RecordType.Id  <>  '01236000001931J' &&  OR(ISBLANK( BillingStreet ), ISBLANK( BillingCity ), ISBLANK( BillingState ), ISBLANK( BillingCountry ), ISBLANK( BillingPostalCode))

Account Trigger:
trigger AccountTrigger on Account (after insert, after update) {
    
    // Set Boolean Value to False to Prevent Recursion
    if(AccountUtil.firstRun == TRUE) {
        AccountUtil.firstRun = FALSE;
        AccountUtil.updateBranchAndCompanyNumber(Trigger.new);
    }
}
               
AccountUtil Class:
public class AccountUtil {
    // Boolean variable to prevent recursion
    public static Boolean firstRun         = TRUE;
    
    public static void updateBranchAndCompanyNumber(List<Account> accountToUpdate) {
        Set<Id> accountIdSet                     = new Set<Id>();
        
        for(Account acct: accountToUpdate) {
            // Add the account to the set, if it has not been last modified by Luxent
            if(acct.LastModifiedById != '00536000002pPlT') {
                accountIdSet.add(acct.OwnerId);
            }
        }
        
        List<User> users = [SELECT     Id,
                                    ATPAC_Company_Number__c,
                                    Branch__c
                            FROM    User
                            WHERE    Id IN :accountIdSet];
        
        Map<ID, User> userMap = new Map<ID, User>();
        
        for(User u : users) {
            userMap.put(u.Id, u);
        }
        System.debug('userMap: ' + userMap);
        
        Map<String, acCore__Company__c> userATPACInfo     = new Map<String, acCore__Company__c>();
        
        for(acCore__Company__c company : [SELECT Id, Name FROM acCore__Company__c]) {
            userATPACInfo.put(company.Name, company);
        }
        System.debug('userATPACInfo: ' + userATPACInfo);
        
        Map<String, acCore__SalesTerritory__c> userBranchInfo     = new Map<String, acCore__SalesTerritory__c>();
        
        for(acCore__SalesTerritory__c branch : [SELECT Id, Name FROM acCore__SalesTerritory__c]) {
            userBranchInfo.put(branch.Name, branch);
        }
        System.debug('userBranchInfo: ' + userBranchInfo);
        
        // Empty List that will update accounts
        List<Account> accountList = new List<Account>();
        
        for(Account acct : accountToUpdate) {
            if(acct.LastModifiedById != '00536000002pPlT') {
                Account toUpdate             = new Account(Id = acct.Id);
                
                // Get the companyName string value from the User Map
                String companyName            = userMap.get(acct.OwnerId).ATPAC_Company_Number__c;
                System.debug('companyName: ' + companyName);
                
                // Ensure that the Company Id is not null
                if(userATPACInfo.get(companyName).Id != null) {
                    toUpdate.acCore__Company__c = userATPACInfo.get(companyName).Id;
                }
                System.debug('toUpdate.acCore__Company__c: ' + toUpdate.acCore__Company__c);
                
                // Get the branchName string value from the User Map
                String branchName = userMap.get(acct.OwnerId).Branch__c;
                System.debug('branchName: ' + branchName);
                
                // Ensure that the Branch Id is not null
                if(userBranchInfo.get(branchName).Id != null) {
                    toUpdate.acCore__SalesTerritory__c    = userBranchInfo.get(branchName).Id;
                }
                System.debug('toUpdate.acCore__SalesTerritory__c: ' + toUpdate.acCore__SalesTerritory__c);
                
                accountList.add(toUpdate);
            }
        }
        update accountList;
    }
Sloan ManaSloan Mana
Since we have all these perameters surrounding our Accounts, would it be possible to create and associate a lead record during the test process instead of a an account or contact? Or, does the test class have to cover accounts?