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
jahnhyjahnhy 

Testing help for Task trigger that relates task to campaign

Hello,
I have created/copied the below trigger code that updates the "related to" in a task to a contact field that contains the sfdc campaign id. I tried deploying without testing and getting the 75% test level, but it appears as inactive in sfdc. Does anyone knnow what code I could use to test this? What steps would be to test and deploy as active?
Thanks in advance,
 

trigger TaskCampaignAssoc on Task (after insert) {

Task[] taskList = [select whoid, ownerid from Task where id in :Trigger.new and ownerid <>'00530000000vpI1'];

Set<Id> setcontactIds = new Set<Id>();

for(Task task: taskList)

{

setcontactIds.add(task.whoid);

}

Contact[] contactList = [select Latest_Campaign_Response__c from contact where id in :setcontactIds];

List<Task> tasksToUpdate = new List<Task>();

for (integer i=0; i<contactList.size();i++)

{

for (Task t : taskList)

{

t.whatid = contactList[i].Latest_Campaign_Response__c;

tasksToUpdate.add(t);

}

}

update (tasksToUpdate);

}

tmatthiesentmatthiesen
A couple of things:

1) no need to requery the tasks - you already have access to the trigger.new collection.  Just filter out the owner ID by looping through trigger.new.
2) change the trigger to before insert
3) create a map (contact id, Latest_Campaign_Response__c) from the query results (against the contact object)
4) iterate through the trigger.new collection(filter out the owner id in an IF statement and simply grab the Lastest_Campaign_Response__c from the map using the task.whoid as the key lookup)
5) since this is a before insert, you don't have to explicitly perform DML - just set the task.whatid as you iterate through the trigger.new collection.

For testing:

I would create a test class:

@isTest
private class TestTaskTrigger {

static testmethod void createTask(){
//create two Campaigns
//create a few Contacts with Contact.Latest_Campaign_Response__c = campaignid (associate a few to each campaign)
//create a set of Tasks - this will invoke the trigger and allow you to test your logic
//query the Tasks and confirm the lastest_campaign_response__c was correctly populated (use the system.assert methods for this)
}

static testmethod void createTasknegative(){
//create a similar test but create a few tasks with the filtered ownerid - as well as create a few contacts that do not have any values populated on the Latest_Campaign_Response__c.  I would also test any possible exceptions as well.

}
}
jahnhyjahnhy
Thanks! It worked and is tested/deployed. Auto associates task to campaign. I had to keep it as an after insert or it doesn't seem to make the association. Thanks again for the assistance.