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
schmichaelschmichael 

Test Class For Task Trigger

Hello All,

 

I modified a trigger I found online to suit my company's needs, but I'm having issues writing a test for it. I'm able to test the first 4 lines no problem, but I'm having issues testing the last two (beginning with the for loop). Can anyone provide assistance?

 

trigger OppTaskContactRole on Task (before insert, before update)
{

    for (Task curr: Trigger.new)
    {
        if (curr.WhatId != null && curr.WhoID == null && curr.WhatId.getsobjecttype()==opportunity.sobjecttype )  {
            List<OpportunityContactRole> roles = [SELECT OpportunityId, ContactId
            FROM OpportunityContactRole
            WHERE isPrimary = true AND OpportunityId = :curr.whatId
            LIMIT 1];
                
            if(!roles.isEmpty()){
                for(OpportunityContactRole ocr : roles){
                    curr.WhoId = ocr.ContactId;
                }
            }
        }
    }
}

gedeefgedeef

hello,

 

I might be wrong but I think that :

 

1st you should not run a query inside a loop, instead build a List<ID> with all the IDs of the opportunities and run your query with a "Where Id in :yourList" condition, outside the loop.

 

2nd, you modify the WhoId field but don't perform the update so that will do nothing.

 

And finally to answer your question, to test the last lines you need to create a task associated with an opportunity associated with a contact.

Eli Flores, SFDC DevEli Flores, SFDC Dev
as a quick correction to#2, it will update the fields because it's a before trigger.

He's right about #1. You want to iterate through trigger new adding each ID Set<ID> , do one query, then iterate through the result map it to map<id,id>.. Then runt through the trigger doing something like curr.whoid = map.containsKey(curr.WhatID) ? map.get(curr.WhatID) : null;
gedeefgedeef

//I was wrong about the update, it's a trigger

//I would do that (or something like, not tested

 

trigger OppTaskContactRole on Task (before insert, before update)
{
List<Id> oppIds = new List<Id>();
    for (Task curr: Trigger.new)
        if (curr.WhatId != null && curr.WhoID == null && curr.WhatId.getsobjecttype()==opportunity.sobjecttype )

            oppIds.add(curr.WhatId);

           

List<OpportunityContactRole> roles = [SELECT OpportunityId, ContactId
            FROM OpportunityContactRole
            WHERE isPrimary = true AND OpportunityId in : oppIds];

 

Map<Id, Id> mapOppContact = new Map<Id, Id>();

for (OpportunityContactRole ocr : roles)

    mapOppContact.put(ocr.OpportunityId, ocr.ContactId);

   
for (Task t : Trigger.new)

     if (curr.WhatId != null && curr.WhoID == null)

        if (mapOppContact.keyExists(t.WhatId))

            t.WhoId = mapOppContact.get(t.WhatId);


}