You need to sign in to do that
Don't have an account?
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!
hi,
set a required field, like lastname to null before uodating. that way it will create required_field_missing exception.
add one more lead in that list with improper data like :
//Test Class
@IsTest
public class AccountHandlerTest{
public static testMethod void insertAccountTest(){
//Cover try block
Account acc = new Account(Name = 'Test Account');
AccountHandler.insertAccount(acc);
//Cover catch block
Account accnt = new Account(); //drop required field to throw exception deliberately
//catch exception you are getting in test class as shown below
try{
AccountHandler.insertAccount(accnt);
}catch(DMLException dex){
System.debug ('all right' + dex.getMessage());
return;
}
System.assert(false, 'a dml exception was expected but was not thrown');
}
}