0

I have an apex code like that :

List<Campaign> campaigns = DataFactory.createCampaign();

    Contact contact = new Contact(/*some fields here*/);
    if(!campaigns.isEmpty()){
        DataFactory.createCampaignMember(campaigns[0], contact);
    }

If I put a system.debug(campaings) I retrieve 3 campaings, so my list campaigns is not empty. But when I run the code (it is in an apex test class) I got this error :

System.ListException: List index out of bounds: 0

at the line DataFactory.createCampaignMember(campaigns[0], contact);

How can I resolve this error ?

EDIT :

Here is the method of the DataFactory :

public static CampaignMember createCampaignMember(Campaign campaign, Contact contact){
  List<Contact> idContact = [SELECT Id FROM Contact WHERE FirstName=:contact.FirstName LIMIT 1];
  List<Campaign> idCampaign = [SELECT Id FROM Campaign WHERE Name=:campaign.Name LIMIT 1];
  CampaignMember campaignMember = new CampaignMember(ContactId=idContact.get(0).Id, CampaignId=idCampaign.get(0).Id);
  return campaignMember;
}

The error is indicated on the line CampaignMember(ContactId=idContact.get(0).Id, CampaignId=idCampaign.get(0).Id);

  • show full test class and full error message with mentioned line – Oleksandr Berehovskyi Sep 19 '18 at 8:12
  • this is a whole test method and the line is the one indicated in the question – dou Sep 19 '18 at 8:43
  • looks like you have problem inside DataFactory.createCampaignMember method – Oleksandr Berehovskyi Sep 19 '18 at 8:44
  • I added the method from the DataFactory and the line indicated by the error message – dou Sep 19 '18 at 8:47
2

in your createCampaignMember method you have List<Contact> idContact = [SELECT Id FROM Contact WHERE FirstName=:contact.FirstName LIMIT 1]; soql that queries Contact.

but from test class you don't insert such contact Contact contact = new Contact(/*some fields here*/); you need to insert this contact.

List<Campaign> campaigns = DataFactory.createCampaign();

Contact cont = new Contact(/*some fields here*/);
insert cont;
if(!campaigns.isEmpty()){
    DataFactory.createCampaignMember(campaigns[0], cont);
}

make sure that List<Campaign> campaigns = DataFactory.createCampaign(); also inserts campaigns to DB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.