You need to sign in to do that
Don't have an account?
jahnhy
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);
}
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.
}
}