function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
John L Schneider IIJohn L Schneider II 

Help adding leads to a campaign in Test Class?

I am working on a unti test that creates leads and then add them to campaign.  Here is the where I am at.  I am currently stuck at how to add the leads created in bulk to the campaign I create in the test class.
 
@isTest
public class UnitTest_Lead {
    static testMethod void runPositiveTestCases(){

        final string givenLastName = 'Weebles';
        try{
        System.debug('Inserting 1 Lead... (single record validation)');
        
        Lead testLead1 = new Lead(LastName = 'Weebles',
                                 Company ='Weebles Widgets');
        insert testLead1;
        
        //Validate single insert
        for(Lead l:[SELECT LastName FROM Lead WHERE
                   CreatedDate = TODAY])

        System.assertEquals(givenLastName, l.LastName);
        }
		catch(DmlException e1) {
		System.debug('An unexpected error has occurred: ' + e1.getMessage());
        }
        
        try{
        //Bulk validation
        System.debug('Inserting 2000 Leads... (bulk validation)');
        
        List<Lead> testLead2 = new List<Lead>();
        for(integer i=0; i<2000; i++) {
            testLead2.add(new Lead(LastName = 'Weebles',Company = 'Weebles Widgets' + i, Email = i+'@weebles.com'));
        }
        insert testLead2;
        }
		catch(DmlException e2) {
		System.debug('An unexpected error has occurred: ' + e2.getMessage());
        }
        
        try{
		//Create a campaign
        Campaign camp1 = new Campaign(Name = 'Test Campaign 1', IsActive = True);
        insert camp1;
        }
		catch(DmlException e3) {
		System.debug('An unexpected error has occurred: ' + e3.getMessage());
        }
        
        try{
        Campaign campID = [SELECT Id FROM Campaign WHERE Name = 'Test Campaign 1'
                           AND IsActive = True AND CreatedDate = :System.today()];
        //Add the bulk contacts to campaign
        //This is where I'm stuck
        List<CampaignMember> testCampMemb1 = new List<CampaignMember>();
        for(integer i=0; i<2000; i++) {
            testCampMemb1.add(new CampaignMember(LeadId__r.Email = i+'@weebles.com', CampaignId = campID, Status = 'Sent'));
        }
        insert testCampMemb1;
            
        }
		catch(DmlException e3) {
		System.debug('An unexpected error has occurred: ' + e3.getMessage());
        }
    }
}

 
Best Answer chosen by John L Schneider II
Ravi Dutt SharmaRavi Dutt Sharma
Hi John,

Try this and let me know if it works for you. Thanks.
 
List<CampaignMember> testCampMemb1 = new List<CampaignMember>();
for(integer i=0; i<2000; i++) {
	testCampMemb1.add(new CampaignMember(LeadId =testLead2.get(i).Id , CampaignId = campID, Status = 'Sent'));
}
insert testCampMemb1;