
I need a litte help with what to to to get better test coverage for a trigger that updates a contact record field with the name of the last campaign event attended. Here is the trigger code:
trigger LastEventAttended on CampaignMember (after insert, after update) {
for(campaignmember cm : trigger.new){
Contact con = new Contact();
List<CampaignMember> cms = [SELECT ID, CampaignId
FROM CampaignMember
WHERE ContactId =: cm.ContactId
AND Status = 'Attended'
ORDER BY Campaign.EndDate DESC
Limit 1];
if(cms.size() > 0) {
Campaign camp = [SELECT Id, Name
FROM Campaign
WHERE Id =: cms[0].CampaignId];
con = [SELECT Id
FROM Contact
WHERE Id =: cm.ContactId];
con.Last_Volunteer_Event__c = camp.Name;
update con;
}
}
}
and here is where I am at with the test class. I am getting 45% coverage:
@isTest
public class LastEventAttendedTest {
//create a contact
static testmethod void createContact() {
Contact c = new Contact();
c.FirstName = 'John';
c.LastName = 'Doe';
insert c;
//create a campaign
Campaign cm = new Campaign();
cm.Name = 'Acme Campaign';
cm.StartDate = date.Today();
cm.EndDate = date.Today();
insert cm;
//add the contact to the campaign with the status of "Prospect"
CampaignMember cpm = new CampaignMember();
cpm.ContactId = c.Id;
cpm.CampaignId = cm.Id;
cpm.Status = 'Prospect';
insert cpm;
//add the contact to the campaign with the status of "Attended"
test.startTest();
cpm.Status = 'Attended';
insert cpm;
test.stopTest();
}
}
Where I seem to be missing coverage is in the IF statement of the trigger wher it's querying for the campaign and contact. I have tried a number of things but unsure how to proceed. Any help will be appreciated!
Hi Ken, Issue was coming due to compaignMemberStatus. Please try below code. I just tested same code in my develope org
Let us know if this will help you@isTest
public class LastEventAttendedTest {
//create a contact
static testmethod void createContact()
{
Contact c = new Contact();
c.FirstName = 'John';
c.LastName = 'Doe';
insert c;
//create a campaign
Campaign cm = new Campaign();
cm.Name = 'Acme Campaign';
cm.StartDate = date.Today();
cm.EndDate = date.Today();
insert cm;
//add the contact to the campaign with the status of "Prospect"
CampaignMember cpm = new CampaignMember();
cpm.ContactId = c.Id;
cpm.CampaignId = cm.Id;
cpm.Status = 'Prospect';
insert cpm;
CampaignMemberStatus cms12 = new CampaignMemberStatus(
CampaignId = cm.Id,
Label = 'Attended',
SortOrder = 3,
IsDefault=true,
HasResponded=false
);
insert cms12;
//add the contact to the campaign with the status of "Attended"
test.startTest();
cpm.Status = 'Attended';
update cpm;
test.stopTest();
}
}