1

I am trying to write test class for a batch job, but I am not able to cover the execute method and to enter in it in order to debug my class. How can I cover this method?

Batch job:

    /**
 * Created by Evgeniya.Zaneva on 27.8.2018 ..
 * track visitors participating orgateg trade fair
 */

public class OrgatecTradeFairBatch implements Schedulable, DataBase.Batchable<sObject> {

    private String campaignId = '7010E000000qSFuQAM';
    private Map<Id, CampaignMember> newCampaignMembers;
    private Map<Id, CampaignMember> updatedCampaignMembers;

    public List<Campaign> start(Database.BatchableContext batchableContext) {

        return [Select Id From Campaign WHERE Id = :campaignId];
    }

    public void execute(Database.BatchableContext bc, List<Campaign> scope) {
        OrgatecDimedisJsonToApex result = getResult();

        List<Lead> leads = new List<Lead>();

        /*
        Map for collecting VIT_MessebarcodeID__c
         */
        Map<String, CampaignMember> campaignMemberMap = new Map<String, CampaignMember>();

        for (CampaignMember member : [SELECT Id,VIT_MessebarcodeID__c FROM CampaignMember WHERE CampaignId = :scope.get(0).Id]) {
            campaignMemberMap.put(member.VIT_MessebarcodeID__c, member);
        }
        /*
            Map for updatedCampaignMembers
         */
        updatedCampaignMembers = new Map<Id, CampaignMember>();

        /*
           Map for matched lead email addresses
         */
        Map<String, Lead> leadEmailAddresses = new Map<String, Lead>();

        /*
           Map for matched contact email addresses
       */
        Map<String, Contact> contactEmailAddresses = new Map<String, Contact>();

        /*
          Set for dimedis email addresses
         */
        Set<String>emailAddresses = new Set<String>();
        /*
            Put each email from dimedis database into a set in order to iterate only over leads or contacts with the same email address
         */
        for (OrgatecDimedisJsonToApex.Records rec : result.records) {
            if (rec.registration.email != null) {
                emailAddresses.add(rec.registration.email);
            }
            if (rec.custom.email != null) {
                emailAddresses.add(rec.custom.email);
            }

        }

        for (Lead lead : [SELECT Email FROM Lead WHERE Email IN:emailAddresses]) {
            leadEmailAddresses.put(lead.Email, lead);
        }

        for (Contact con : [SELECT Email FROM Contact WHERE Email IN:emailAddresses]) {
            contactEmailAddresses.put(con.Email, con);
        }
        /*

         */
        for (OrgatecDimedisJsonToApex.Records rec : result.records) {
            if (!campaignMemberMap.containsKey(rec.scan_barcode)) {

                if (leadEmailAddresses.containsKey(rec.custom.email) || leadEmailAddresses.containsKey(rec.registration.email)) {
                    CampaignMember cm = new CampaignMember();
                    cm.CampaignId = campaignId;
                    String customId = contactEmailAddresses.get(rec.custom.email).Id;
                    String registrationId = contactEmailAddresses.get(rec.registration.email).Id;
                    cm.LeadId = customId == null ? registrationId : customId;
                    cm.Status = 'Attended';
                    updatedCampaignMembers.put(cm.Id, cm);
                } else {
                    Lead lead = new Lead();
                    lead.Email = rec.registration.email;
                    lead.Country = rec.registration.country == 'DE' ? lead.Country : 'Germany';
                    lead.Street = rec.registration.street;
                    lead.Company = rec.registration.company;
                    lead.FirstName = rec.registration.first_name;
                    lead.LastName = rec.registration.last_name;
                    lead.City = rec.registration.city;
                    lead.CountryCode = rec.registration.country;
                    lead.PostalCode = rec.registration.zip;
                    leads.add(lead);
                }
                if (contactEmailAddresses.containsKey(rec.custom.email) || contactEmailAddresses.containsKey(rec.registration.email)) {
                    CampaignMember cm = new CampaignMember();
                    cm.CampaignId = campaignId;
                    String customId = contactEmailAddresses.get(rec.custom.email).Id;
                    String registrationId = contactEmailAddresses.get(rec.registration.email).Id;
                    cm.ContactId = customId == null ? registrationId : customId;
                    cm.Status = 'Attended';
                    updatedCampaignMembers.put(cm.Id, cm);
                } else {
                    Lead lead = new Lead();
                    lead.Email = rec.registration.email;
                    lead.Country = rec.registration.country == 'DE' ? lead.Country : 'Germany';
                    system.debug('Lead country****************' + lead.Country);
                    lead.Street = rec.registration.street;
                    lead.Company = rec.registration.company;
                    lead.FirstName = rec.registration.first_name;
                    lead.LastName = rec.registration.last_name;
                    lead.City = rec.registration.city;
                    lead.CountryCode = rec.registration.country;
                    lead.PostalCode = rec.registration.zip;
                    leads.add(lead);
                }
            }
        }
        insert leads;
        createCampaignMember(leads);
        insert newCampaignMembers.values();
        update updatedCampaignMembers.values();
    }
    public void finish(Database.BatchableContext batchableContext) {
    }

    public void execute(SchedulableContext schedulableContext) {
        OrgatecTradeFairBatch cmBatch = new OrgatecTradeFairBatch();
        Database.executeBatch(cmBatch);
    }
    private void createCampaignMember(List<Lead> leads) {
        newCampaignMembers = new Map<Id, CampaignMember>();
        for (Lead l : leads) {
            CampaignMember cm = new CampaignMember();
            cm.CampaignId = campaignId;
            cm.LeadId = l.Id;
            cm.Status = 'Attended';
            newCampaignMembers.put(cm.Id, cm);
        }
    }
    private OrgatecDimedisJsonToApex getResult() {
        return OrgatecDimedisJsonToApex.parse(getJson());
    }

    private String getJson() {
        return '{  ' +
                '   \"timestamp\":\"2018-08-28 15:20:20\",' +
                '   \"total_count\":3,' +
                '   \"max_page_size\":30,' +
                '   \"current_page_size\":3,' +
                '   \"row_offset\":0,' +
                '   \"order_by\":\"scan_timestamp\",' +
                '   \"direction\":\"asc\",' +
                '   \"records\":[  ' +
                '      {  ' +
                '         \"scan_barcode\":\"0Oq9RM1hF1aFu\",' +
                '         \"scan_timestamp\":\"2018-08-23 17:35:14\",' +
                '         \"custom_status\":\"empty\",' +
                '         \"contact_rating\":\"empty\",' +
                '         \"registration\":{  ' +
                '            \"country\":\"DE\",' +
                '            \"newsletter\":\"empty\",' +
                '            \"note\":\"empty\",' +
                '            \"house_no_extension\":\"empty\",' +
                '            \"city2\":\"empty\",' +
                '            \"gender\":\"w\",' +
                '            \"street3\":\"empty\",' +
                '            \"street4\":\"empty\",' +
                '            \"city\":\"Elsenfeld\",' +
                '            \"user_name\":\"empty\",' +
                '            \"mobile_area_code\":\"empty\",' +
                '            \"title\":\"empty\",' +
                '            \"division\":\"empty\",' +
                '            \"company2\":\"empty\",' +
                '            \"street\":\"Teststra?e\",' +
                '            \"company3\":\"empty\",' +
                '            \"company4\":\"empty\",' +
                '            \"company\":\"dimedis TEST GEW\",' +
                '            \"street2\":\"empty\",' +
                '            \"webpage\":\"empty\",' +
                '            \"fax\":\"empty\",' +
                '            \"first_name\":\"Ellen\",' +
                '            \"email\":\"20170620_5@testmail.dimedis.de\",' +
                '            \"area\":\"empty\",' +
                '            \"zip\":\"63820\",' +
                '            \"zip_pobox\":\"empty\",' +
                '            \"address_suid\":\"dim.a.grappa.2017062009-20-54.33308.22304.1\",' +
                '            \"last_name\":\"Wagner\",' +
                '            \"title2\":\"empty\",' +
                '            \"mobile_extension\":\"empty\",' +
                '            \"accreditation_type\":\"empty\",' +
                '            \"pobox\":\"empty\",' +
                '            \"phone\":\"empty\",' +
                '            \"house_no\":\"36\",' +
                '            \"salutation\":\"empty\",' +
                '            \"zip_street\":\"empty\",' +
                '            \"position\":\"empty\",' +
                '            \"region\":\"empty\"' +
                '         },' +
                '         \"custom\":{  ' +
                '            \"country\":\"\",' +
                '            \"newsletter\":\"\",' +
                '            \"note\":\"empty\",' +
                '            \"house_no_extension\":\"\",' +
                '            \"city2\":\"\",' +
                '            \"gender\":\"empty\",' +
                '            \"street3\":\"\",' +
                '            \"street4\":\"\",' +
                '            \"city\":\"\",' +
                '            \"user_name\":\"\",' +
                '            \"mobile_area_code\":\"\",' +
                '            \"title\":\"\",' +
                '            \"division\":\"\",' +
                '            \"company2\":\"\",' +
                '            \"street\":\"\",' +
                '            \"company3\":\"\",' +
                '            \"company4\":\"\",' +
                '            \"company\":\"\",' +
                '            \"street2\":\"\",' +
                '            \"webpage\":\"\",' +
                '            \"fax\":\"\",' +
                '            \"first_name\":\"\",' +
                '            \"email\":\"\",' +
                '            \"area\":\"\",' +
                '            \"zip\":\"\",' +
                '            \"zip_pobox\":\"\",' +
                '            \"last_name\":\"\",' +
                '            \"title2\":\"\",' +
                '            \"mobile_extension\":\"\",' +
                '            \"pobox\":\"\",' +
                '            \"deleted\":\"false\",' +
                '            \"phone\":\"\",' +
                '            \"house_no\":\"\",' +
                '            \"salutation\":\"\",' +
                '            \"zip_street\":\"\",' +
                '            \"position\":\"\",' +
                '            \"region\":\"\"' +
                '         },' +
                '         \"selected_tags\":[  ' +
                '' +
                '         ],' +
                '         \"survey\":\"empty\"' +
                '      },' +
                '      {  ' +
                '         \"scan_barcode\":\"w0pGRA1iiZ6TF\",' +
                '         \"scan_timestamp\":\"2018-08-28 15:28:19\",' +
                '         \"custom_status\":\"empty\",' +
                '         \"contact_rating\":\"empty\",' +
                '         \"registration\":{  ' +
                '            \"country\":\"DE\",' +
                '            \"newsletter\":\"empty\",' +
                '            \"note\":\"empty\",' +
                '            \"house_no_extension\":\"empty\",' +
                '            \"city2\":\"empty\",' +
                '            \"gender\":\"w\",' +
                '            \"street3\":\"empty\",' +
                '            \"street4\":\"empty\",' +
                '            \"city\":\"Koln\",' +
                '            \"user_name\":\"empty\",' +
                '            \"mobile_area_code\":\"empty\",' +
                '            \"title\":\"empty\",' +
                '            \"division\":\"empty\",' +
                '            \"company2\":\"empty\",' +
                '            \"street\":\"Muhlenstra?e\",' +
                '            \"company3\":\"empty\",' +
                '            \"company4\":\"empty\",' +
                '            \"company\":\"dimedis TEST GEW\",' +
                '            \"street2\":\"empty\",' +
                '            \"webpage\":\"empty\",' +
                '            \"fax\":\"empty\",' +
                '            \"first_name\":\"Hannah\",' +
                '            \"email\":\"20170620_12@testmail.dimedis.de\",' +
                '            \"area\":\"empty\",' +
                '            \"zip\":\"51105\",' +
                '            \"zip_pobox\":\"empty\",' +
                '            \"address_suid\":\"dim.a.grappa.2017062010-33-40.1483.31117.1\",' +
                '            \"last_name\":\"Scholz\",' +
                '            \"title2\":\"empty\",' +
                '            \"mobile_extension\":\"empty\",' +
                '            \"accreditation_type\":\"empty\",' +
                '            \"pobox\":\"empty\",' +
                '            \"phone\":\"empty\",' +
                '            \"house_no\":\"53\",' +
                '            \"salutation\":\"empty\",' +
                '            \"zip_street\":\"empty\",' +
                '            \"position\":\"empty\",' +
                '            \"region\":\"empty\"' +
                '         },' +
                '         \"custom\":{  ' +
                '            \"country\":\"DE\",' +
                '            \"newsletter\":\"\",' +
                '            \"note\":\"empty\",' +
                '            \"house_no_extension\":\"\",' +
                '            \"city2\":\"\",' +
                '            \"gender\":\"w\",' +
                '            \"street3\":\"\",' +
                '            \"street4\":\"\",' +
                '            \"city\":\"Koln\",' +
                '            \"user_name\":\"\",' +
                '            \"mobile_area_code\":\"\",' +
                '            \"title\":\"\",' +
                '            \"division\":\"\",' +
                '            \"company2\":\"\",' +
                '            \"street\":\"Muhlenstra?e\",' +
                '            \"company3\":\"\",' +
                '            \"company4\":\"\",' +
                '            \"company\":\"dimedis TEST GEW\",' +
                '            \"street2\":\"\",' +
                '            \"webpage\":\"\",' +
                '            \"fax\":\"\",' +
                '            \"first_name\":\"Hannah\",' +
                '            \"email\":\"20170620_12@testmail.dimedis.de\",' +
                '            \"area\":\"\",' +
                '            \"zip\":\"51105\",' +
                '            \"zip_pobox\":\"\",' +
                '            \"last_name\":\"Scholz\",' +
                '            \"title2\":\"\",' +
                '            \"mobile_extension\":\"\",' +
                '            \"pobox\":\"\",' +
                '            \"deleted\":\"false\",' +
                '            \"phone\":\"\",' +
                '            \"house_no\":\"53\",' +
                '            \"salutation\":\"\",' +
                '            \"zip_street\":\"\",' +
                '            \"position\":\"\",' +
                '            \"region\":\"\"' +
                '         },' +
                '         \"selected_tags\":[  ' +
                '' +
                '         ],' +
                '         \"survey\":\"empty\"' +
                '      },' +
                '      {  ' +
                '         \"scan_barcode\":\"YjFjfY2V2SO9A\",' +
                '         \"scan_timestamp\":\"2018-08-23 16:53:07\",' +
                '         \"custom_status\":\"empty\",' +
                '         \"contact_rating\":\"empty\",' +
                '         \"registration\":{  ' +
                '            \"country\":\"DE\",' +
                '            \"newsletter\":\"empty\",' +
                '            \"note\":\"empty\",' +
                '            \"house_no_extension\":\"empty\",' +
                '            \"city2\":\"empty\",' +
                '            \"gender\":\"m\",' +
                '            \"street3\":\"empty\",' +
                '            \"street4\":\"empty\",' +
                '            \"city\":\"Grunewald\",' +
                '            \"user_name\":\"empty\",' +
                '            \"mobile_area_code\":\"empty\",' +
                '            \"title\":\"empty\",' +
                '            \"division\":\"empty\",' +
                '            \"company2\":\"empty\",' +
                '            \"street\":\"Vogelstra?e\",' +
                '            \"company3\":\"empty\",' +
                '            \"company4\":\"empty\",' +
                '            \"company\":\"dimedis TEST GEW\",' +
                '            \"street2\":\"empty\",' +
                '            \"webpage\":\"empty\",' +
                '            \"fax\":\"empty\",' +
                '            \"first_name\":\"Alfred\",' +
                '            \"email\":\"20170620_9@testmail.dimedis.de\",' +
                '            \"area\":\"empty\",' +
                '            \"zip\":\"01945\",' +
                '            \"zip_pobox\":\"empty\",' +
                '            \"address_suid\":\"dim.a.grappa.2017062009-45-21.13418.5964.1\",' +
                '            \"last_name\":\"Peters\",' +
                '            \"title2\":\"empty\",' +
                '            \"mobile_extension\":\"empty\",' +
                '            \"accreditation_type\":\"empty\",' +
                '            \"pobox\":\"empty\",' +
                '            \"phone\":\"empty\",' +
                '            \"house_no\":\"56\",' +
                '            \"salutation\":\"empty\",' +
                '            \"zip_street\":\"empty\",' +
                '            \"position\":\"empty\",' +
                '            \"region\":\"empty\"' +
                '         },' +
                '         \"custom\":{  ' +
                '            \"country\":\"\",' +
                '            \"newsletter\":\"\",' +
                '            \"note\":\"empty\",' +
                '            \"house_no_extension\":\"\",' +
                '            \"city2\":\"\",' +
                '            \"gender\":\"empty\",' +
                '            \"street3\":\"\",' +
                '            \"street4\":\"\",' +
                '            \"city\":\"\",' +
                '            \"user_name\":\"\",' +
                '            \"mobile_area_code\":\"\",' +
                '            \"title\":\"\",' +
                '            \"division\":\"\",' +
                '            \"company2\":\"\",' +
                '            \"street\":\"\",' +
                '            \"company3\":\"\",' +
                '            \"company4\":\"\",' +
                '            \"company\":\"\",' +
                '            \"street2\":\"\",' +
                '            \"webpage\":\"\",' +
                '            \"fax\":\"\",' +
                '            \"first_name\":\"\",' +
                '            \"email\":\"\",' +
                '            \"area\":\"\",' +
                '            \"zip\":\"\",' +
                '            \"zip_pobox\":\"\",' +
                '            \"last_name\":\"\",' +
                '            \"title2\":\"\",' +
                '            \"mobile_extension\":\"\",' +
                '            \"pobox\":\"\",' +
                '            \"deleted\":\"false\",' +
                '            \"phone\":\"\",' +
                '            \"house_no\":\"\",' +
                '            \"salutation\":\"\",' +
                '            \"zip_street\":\"\",' +
                '            \"position\":\"\",' +
                '            \"region\":\"\"' +
                '         },' +
                '         \"selected_tags\":[  ' +
                '' +
                '         ],' +
                '         \"survey\":\"empty\"' +
                '      }' +
                '   ]' +
                '}';

    }
}

And the beggining of my test class

    /**
 * Created by Evgeniya.Zaneva on 27.8.2018 ..
 */
@isTest
public class OrgatecTradeFairBatchTest {
    private static Account acc;
    private static Contact con;
    private static Campaign campaign;
    private static Lead lead;
    private static CampaignMember campaignMember;
    private static OrgatecDimedisJsonToApex dimedisInfo;

    public static void setup() {
        acc = MockupFactory.createAccount('Test Account');
        insert acc;
        con = MockupFactory.createContact('Test Contact', acc.Id);
        insert con;

        dimedisInfo = OrgatecDimedisJsonToApex.parse(getJson());
        system.debug('Dimedis info *********' + dimedisInfo.records);

        campaign = new Campaign();
        campaign.Name = 'Orgatec';
        insert campaign;

        lead = New Lead();
        lead.LastName = 'Orgatec Lead';
        lead.Company = 'Dimedis';
        lead.Email = '20170620_9@testmail.dimedis.de';
        lead.CountryCode = 'DE';
        insert lead;

        campaignMember = new CampaignMember();
        campaignMember.LeadId = lead.Id;
        campaignMember.CampaignId = campaign.Id;
        insert campaignMember;
    }

    @isTest
    private static void campaignMemberCheck() {
        setup();
        Test.startTest();
        Database.executeBatch(new OrgatecTradeFairBatch());
        Test.stopTest();
        Lead l = [SELECT Id,FirstName,Email FROM Lead WHERE Email = :'20170620_9@testmail.dimedis.de'];
        String email;
        for (OrgatecDimedisJsonToApex.Records info : dimedisInfo.records) {
            email = info.registration.email;
        }
        System.assertEquals(l.Email, email);
    }

    private static String getJson() {
        return  - -- the same as the batch job.
    }
}
2

Onet thing I can notice in the code is that the campaignId is hardcoded in the batch job, sorry if this was done only for the purpose of the example.

In the start of the batch class you're setting it to below:

private String campaignId = '7010E000000qSFuQAM';

However in your test method you're creating a new Campaign in setup method:

campaign = new Campaign();
campaign.Name = 'Orgatec';
insert campaign;

Because of this this the Id of the inserted campaign in the test will be different every time the test is executed.

You might need to change the start method of the batch job to fetch campaigns in the system based on different criteria rather than hardcoding the campaign id directly.

Also it might be better to use

public Database.QueryLocator start(Database.BatchableContext bc) {

    //Your query - amend as you need
    return Database.getQueryLocator(
       'Select Id From Campaign'
    );
}

This way you can retrieve up to 50 million records.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm

1

I got similar situation a few months back, then I come to find that I have hardcoded some id in start method of Batch class.

The same mistake you are doing here. What you are doing here is:-

  • private String campaignId = '7010E000000qSFuQAM';

The above string variable contains id which is in your org, but as you have not mention SeeallData=true, the execute method is not covering in your test class. It is because your test class could not found the campaign with the same id in your test data.

If your code really requires that Campaign id campaignId = '7010E000000qSFuQAM';, then you need to use seealldata=true. Otherwise, You can make it dynamic and can proceed as you are doing.

Note:- It is not the best practise to use seealldata=true for your test classes

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.