+ Start a Discussion
snyhansnyhan 

Please help! DML Exception not covered by test class

I've created a trigger, but cannot figure out how to cover the dml exception in my test class. Please help! Trigger & test included below:

 

trigger LeadRespondedToCampaign on CampaignMember (after update) {
//update Lead Score by adding a value (10) to the Lead Responded to Campaign field
//if the Campaign Member Status is "Responded"

    List<id> leadIds=new List<Id>();
   
    for(CampaignMember cm:trigger.new){
        if(cm.LeadId !=null){
            System.debug('Status is ' + cm.Status);
            if(cm.Status=='Responded'){
                leadIds.add(cm.LeadId);
                System.debug('Id is ' + cm.LeadId);
            }
        }
    }
    List<Lead> leads=[SELECT Id, Lead_Responded_to_Campaign__c FROM Lead WHERE Id IN: leadIds];
   
    for(Lead l:leads){
        System.debug('Found lead ' + l);
        l.Lead_Responded_to_Campaign__c=10;
    }
    try{
    update leads;
    System.debug('Leads to update list size ' + leads.size());
    }catch (Dmlexception e){
        system.debug('lead update failed: '+e);
    }
}

 

 

 

@isTest
private class TestLeadRespondedToCampaign {

    static testMethod void testStatusChange() {
        Campaign newc = new Campaign(Name = 'Test Campaign', IsActive = True);
        insert newc;
       
        Lead[] newl = new Lead[]{
            new Lead(FirstName = 'Barbara', LastName = 'Jones', State = 'HI'),
            new Lead(FirstName = 'Tim', LastName = 'McElroy', State = 'NH')
        };
        insert newl;
               
        CampaignMember[] cm = new CampaignMember[]{
            new CampaignMember(CampaignId = newc.id, LeadId = newl[0].id, Status = 'Sent'),
            new CampaignMember(CampaignId = newc.id, LeadId = newl[1].id, Status = 'Sent')
        };
        insert cm;
       
        cm[0].Status = 'Responded';
           Test.StartTest();
        update cm;
           Test.StopTest();
         
          newl = [SELECT id, Lead_Responded_to_Campaign__c FROM Lead WHERE id IN :newl];
          {system.assertEquals(String.valueOf(newl[0].Lead_Responded_to_Campaign__c), '10');
          }
    }
}

 

Thank you!

rohitsfdcrohitsfdc

hi,

set a required field, like lastname  to null before uodating. that way it will create required_field_missing exception.

Rahul SharmaRahul Sharma

add one more lead in that list with improper data like :

 

 

  Lead[] newl = new Lead[]{
	new Lead(FirstName = 'Barbara', LastName = 'Jones', State = 'HI'),
	new Lead(FirstName = 'Tim', LastName = 'McElroy', State = 'NH'),
	new Lead(LastName = 'test', State = '12')
        };