+ Start a Discussion
krish99krish99 

test class for trigger help

HI,

          i wrote a trigger, it is working good, i write a test class for it the test class is also passed but trigger code coverage is showing 66% only how can i increase the trigger code to 75%. any help

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

    Map<String, Lead> leadMap = new Map<String, Lead>();

    for (Lead lead : System.Trigger.new) 
     {  

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

            if (leadMap.containsKey(lead.LastName)) 
           {

                lead.LastName.addError('Another new lead has the '  + 'same LastName address.');

            } 
               else {

                leadMap.put(lead.LastName, lead);

            }

       }

    }   

    for (Lead lead : [SELECT LastName FROM Lead WHERE LastName IN :leadMap.KeySet()]) 
     {

        Lead newLead = leadMap.get(lead.LastName);

        newLead.LastName.addError('A lead with this LastName ' + 'address already exists.');

    }

}

   @test class for trigger

@istest public class TestleadDuplicatePreventer2 
{ 
Private Static testmethod void TestleadDuplicatePreventer2()
{ 
Lead objLead = new Lead(); 
objLead.LastName = 'Test Lead'; 
objLead.Company = 'Test Lead'; 
objLead.Status = 'Test LeadStatus'; 
objLead.LeadSource = 'Test LeadSource'; 
insert objLead; 
Lead objLead1 = new Lead(); 
objLead1.LastName = 'Test Lead2'; 
objLead1.Company = 'Test Lead2'; 
objLead1.Status = 'Test LeadStatus2'; 
objLead1.LeadSource = 'Test LeadSource2'; 
insert objLead1; 


} 
}

 

Best Answer chosen by Admin (Salesforce Developers) 
magicforce9magicforce9

Hi,

 

You need to insert two lead records with the same LastName for your trigger to actually execute the login and prevent duplication..so here what you should do

 

In your test class you need to add the insert within a try/catch statement, and add in assertion in the catch statement verifying the error message received is the error message you passed in.

@istest public class TestleadDuplicatePreventer2 
{ 
Private Static testmethod void TestleadDuplicatePreventer2()
{ 
Lead objLead = new Lead(); 
objLead.LastName = 'Test Lead'; 
objLead.Company = 'Test Lead'; 
objLead.Status = 'Test LeadStatus'; 
objLead.LeadSource = 'Test LeadSource'; 
insert objLead; 
Lead objLead1 = new Lead(); 
//Using the same Last Name
objLead1.LastName = 'Test Lead'; 
objLead1.Company = 'Test Lead2'; 
objLead1.Status = 'Test LeadStatus2'; 
objLead1.LeadSource = 'Test LeadSource2'; 
try{
insert objLead1; 
}catch(Exception e){
system.assertEquals(e.getMessage(), 'Your Error message');
}

} 
}