Context: I am trying to build a dupe counter that counts how many Leads match based on the Email value field. Here is the trigger:
//Look for duplicate contacts based on email
//Populate a Dupe_Lead_Counter__c field with a number value if >0 matches found
trigger CountDupeLeads on Lead (before insert, before update) {
for (Lead l : Trigger.new) {
//Make sure our lead has an email address
if (l.Email != null) {
//Find a dupe
String leadEmail = l.Email;
List<Lead> dupeLeads = [SELECT Id FROM Lead WHERE Email = :leadEmail];
//If a dupe is found, update a field
if (dupeLeads.size() > 0) {
l.Dupe_Lead_Counter__c = dupeLeads.size();
} else {
//0 would designate a true unique
l.Dupe_Lead_Counter__c = 0;
}
//want 'null' to distinguish Leads disqualified from the lookup versus true uniques
} else {
l.Dupe_Lead_Counter__c = null;
}
}
}
I then created a @isTest class:
@isTest
public class TestCountingDupes {
static testMethod void testDupeCounter() {
//Principle #ls: Create recordsd from Scratch
Lead dupeLead1 = new Lead();
dupeLead1.FirstName = 'Peter';
dupeLead1.LastName = 'Parker';
dupeLead1.Email = 'spiderman@gmail.com';
dupeLead1.Company = 'Tryler McTrevor Inc';
insert dupeLead1;
Lead dupeLead2 = new Lead();
dupeLead2.FirstName = 'Jane';
dupeLead2.LastName = 'Seymour';
dupeLead2.Email = 'spiderman@gmail.com';
dupeLead2.Company = 'Tryler McTrevor TEST Inc';
insert dupeLead2;
//Principle #2 use System.assertEquals()
dupeLead1 = [SELECT Id, Dupe_Lead_Counter__c FROM Lead LIMIT 1];
System.assertEquals(2, dupeLead2.Dupe_Lead_Counter__c);
//Principle #3: test things that shouldn't work!
dupeLead2.Email = 'janeseymour@gmail.com';
update dupeLead2;
dupeLead1 = [SELECT Id, Dupe_Lead_Counter__c FROM Lead LIMIT 1];
System.assertEquals(0, dupeLead2.Dupe_Lead_Counter__c);
}
}
and the latest error I get from running the test is this:
System.AssertException: Assertion Failed: Expected: 2, Actual: null Class.TestCountingDupes.testDupeCounter
Clearly my trigger logic is populating a null value in that field before the Update action (when it should be the number 2), but I am at a loss--is it the way my @isTest is constructed with Lead record inserts and then updates or is it a systemic issue with my Apex trigger?