You need to sign in to do that
Don't have an account?
Hunter Allspaugh
Unit tests for "before insert" trigger returning null field
I'm trying to create a unit test class for a trigger that fires before insert on Leads so that Lead.Country will be used to lookup the Region (continent) from a custom Country__c table.
If I run a test insert, it will apply the correct Region value to the lead, but when I run unit tests to try to validate the behavior, it returns Null when the lookup to the country table happens.
My trigger code is:
However, when building a unit test to attempt to get the Region, "Africa", the Country__c SOQL query in the trigger returns null:
If I run a test insert, it will apply the correct Region value to the lead, but when I run unit tests to try to validate the behavior, it returns Null when the lookup to the country table happens.
My trigger code is:
trigger LeadsSetRegion on Lead (before insert) { for (Lead l: Trigger.new){ // Query for name of Region that contains Country try { Country__c[] countries = [Select Region__c FROM Country__c WHERE Name=:l.Country]; System.debug(countries); if (countries.size() > 0){ l.Region__c = countries[0].Region__c; } }catch (exception e){ System.debug(e); } } }As stated before, this works perfectly fine when a lead is inserted.
However, when building a unit test to attempt to get the Region, "Africa", the Country__c SOQL query in the trigger returns null:
@isTest public class TestLeadsSetRegion { @isTest public static void TestLeadWithKnownCountry (){ Lead l = new Lead(firstName='Test',lastName='Lead',company='Test Company',email='testlead123@test.com',Country='Nigeria',LeadSource='Contact Us'); // Begin Testing Test.startTest(); insert l; Test.stopTest(); System.assertEquals('Africa', l.Region__c); } }Do I need to perform the lookup in a certain manner to retrieve these results?
If text tyy ths
if its lkp try this
It is a text field. In the case of your first solution, I won't want the inserted record to already have the correct value for Region__c because it won't be submitted with the form to create the Lead.
It needs to be set in the trigger based on the value in the Country field.
If I took lines 6-8 and create the Region object and insert it before inserting the test lead, and then perform a lookup on the newly inserted lead, the appropriate results are returned. The working unit test code is: