+ Start a Discussion
snyhansnyhan 

Help with Apex Test Class

I have created a trigger (posted below) to update a lead field with a number when the Campaign Member Status is changed to 'Responded', however I am having trouble writing the test code for it. The test class I created came back with a warning that 0% of my trigger was covered by the test class. If anyone can please help me write the test I would greatly appreciate your help!

 

Here is the trigger:

trigger LeadRespondedToCampaign on CampaignMember (after update) {
    List<id> leadIds=new List<Id>();
    for(CampaignMember cm:trigger.new){
        if(cm.LeadID!=null){
            if(cm.Status=='Responded'){
                leadIds.add(cm.LeadId);
            }
        }
    }
    List<Lead> leads=[SELECT Id, Lead_Responded_to_Campaign__c FROM Lead WHERE Id IN: leadIds];
    for(Lead l:leads){
        l.Lead_Responded_to_Campaign__c=10;
    }
}

AnushaAnusha

Write one Test Class and in that Insert Record for CampaignMenber or else Query the CampaignMenber.

then update that record in TestClass. It will just Updates in that time only

snyhansnyhan

Thanks, Anusha. I think I'm in way over my head here with trying to write a test class. I wrote a test class I thought would insert a record for campaign member, however I got a warning saying 0% of my code was covered. Here's what I created:

 

@isTest

private class TestLeadRespondedToCampaign {

 

static testMethod void testStatusChange() {

 

Campaign newc = new Campaign(Name = 'Test Campaign', IsActive = True, Status = 'Sent');

 

insert newc;

 

Lead[] l = new Lead[]{

 

new Lead(FirstName = 'Bob', LastName = 'Smith', State = 'NJ', Status = 'Active'),

 

new Lead(FirstName = 'Janet', LastName = 'Pom', State = 'OH', Status = 'Active')

};

insert l;

 

CampaignMember[] cm = new CampaignMember[]{

 

new CampaignMember(CampaignId = newc.Id, LeadId = l[ 0].Id),

 

new CampaignMember(CampaignId = newc.Id, LeadId = l[ 1].Id)

};

insert cm;

 

cm[ 0].Status = 'Sent'; //don't change status

cm[ 1].Status = 'Responded'; //change status

Test.StartTest();

update l;

Test.StopTest();

 

cm = [SELECT Id, Status FROM CampaignMember WHERE id IN:cm];

 

system.assert(l[ 0].Lead_Responded_to_Campaign__c == 10); //unchanged

system.assert(l[ 1].Lead_Responded_to_Campaign__c == 10); //changed

}

}