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
NlandNland 

Trigger for Leads before insert....

I have been trying to write a test class for this trigger, but have been unsuccessful on getting the code coverage that I need to move it into production. 

 

trigger LeadAssignmentTrigger on Lead (before insert) 
{    
    List<String> zips = new List<String>();

    // Loop through Leads and create list of zip codes
    for (Lead lead : Trigger.new)
    {
        if (lead.PostalCode != NULL && lead.Assign_Using_Assignment_Rules__c == true)
        {
            zips.add(lead.PostalCode);    
        }
    }

    //query zip code table and link zips to Sales reps
    Map<String, Zip_Code__c> leadsToUpdate = new Map<String, Zip_Code__c>();

    for(Zip_Code__c zip_code:[select Name, Owner.Id from Zip_Code__c where Name in :zips]) 
    { 
       if(zip_code.Name != null) leadsToUpdate.put(zip_code.Name, zip_code);
    } 


    // If there is at least one match, bulk update
    if (leadsToUpdate.size() > 0)
    {
        
        for (Lead lead : Trigger.new)
        {
            // only update if the lead zip code exists in the Map
            if (leadsToUpdate.containsKey(lead.PostalCode))
            {
              //assign the lead owner to the zip code owner
              lead.OwnerId = leadsToUpdate.get(lead.PostalCode).OwnerId;    
            }
        }
          
     }     
}

Any help would be very much appreciated....

Thanks

NL

Anup JadhavAnup Jadhav

Hello there,

 

To ensure that you cover all scenarios in the trigger, make sure that you create your data inside your test class.

 

Follow these steps:

 

1. Create Zip_Code__c objects and insert them in the database

2. Create several Lead objects with a) null postal code b) non-null postal code

 

When you insert these Lead objects, it should fire this trigger and cover the if loop and for loop. Of course the goal of your testing should be verifying the data after you've inserted it into the database, and not just superficially increasing code coverage in test classes.

 

Hope this helps!

 

- A J