+ Start a Discussion

Code coverage For Trigger which prevents user from entering duplicate emails

trigger leadDuplicatePreventer on Lead 
(before insert, before update) { 

Map<String, Lead> leadMap = new Map<String, Lead>(); 
for (Lead lead : System.Trigger.new) { 

// Make sure we don't treat an email address that 

// isn't changing during an update as a duplicate. 

if ((lead.Email != null) && 
(System.Trigger.isInsert || 
(lead.Email != 
System.Trigger.oldMap.get(lead.Id).Email))) { 

// Make sure another new lead isn't also a duplicate 

if (leadMap.containsKey(lead.Email)) { 
lead.Email.addError('Another new lead has the ' 
+ 'same email address.'); 
} else { 
leadMap.put(lead.Email, lead); 

// Using a single database query, find all the leads in 

// the database that have the same email address as any 

// of the leads being inserted or updated. 

for (Lead lead : [SELECT Email FROM Lead 
WHERE Email IN :leadMap.KeySet()]) { 
Lead newLead = leadMap.get(lead.Email); 
newLead.Email.addError('A lead with this email ' 
+ 'address already exists.'); 
Test Class:
Public class TestEmailDupPreventor
 Public Static testmethod void PositiveCase()
//Testing at the time of record creation
Lead Ld=new Lead(Firstname='Manohar',Lastname='SD',Company='Suzlon',Email='abcd@yopmail.com');
insert ld;
Lead Ld1=new Lead(Firstname='Mohan',Lastname='SD',Company='Suzlon',Email='abcd@yopmail.com');
insert ld1;
catch(DMLException e)
    //System.assert(false,' FIELD_CUSTOM_VALIDATION_EXCEPTION ');

Public Static testmethod void NegativeCase()
//testing for Updation case
Lead l1= new Lead(Firstname='Test1',Lastname='TT',Company='KT',Email='kt1@yopmail.com');insert l1;
Lead l2= new Lead(Firstname='Test2',Lastname='TT',Company='KT',Email='kt2@yopmail.com');insert l2;
upsert l2;
catch(Dmlexception e)

Total coverage is 76%.
The first methode(Checking while Inserting) is executing Properly.
Second method(Checking while Updating) is not passed and showing an error:

System.UnexpectedException: No more than one executeBatch can be called from within a testmethod. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

But I hav'nt wrote any batch methods.