[SalesForce] Test Class not covering the execute method

This batch class is to set the recordtype when it is null.

global class ContactBatch implements Database.Batchable<SObject> {
    global String query;
    global Database.QueryLocator start(Database.BatchableContext BC) {
        query = 'SELECT RecordTypeId, RecordType.name, Email, Account.Name FROM Contact WHERE RecordTypeId = null';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<SObject> batchRecords) {

        Map<String, Schema.RecordTypeInfo> CON_RECORD_TYPES = Schema.SObjectType.Contact.getRecordTypeInfosByName();
        String CON_RECORD_TYPES_ID = CON_RECORD_TYPES.get('PRIMARY DEALER').getRecordTypeId();

        for(SObject c : BatchRecords) {
            Contact con = (Contact)c;
            con.RecordTypeId = CON_RECORD_TYPES_ID;
            update con;
        }
    }
    global void finish(Database.BatchableContext BC) {
    }
}

The batch execute() method is not covered in the test. This should be because the query in the start method is not returning any records. We cannot set the recordtype to null in the test class. How to run the execute() method.

@isTest
public class ContactBatchTest {

    static TestMethod void UnitTest1() {

        Account a = new Account();         
        a.Name = 'Test Dealer';  
        insert a;

        List<Contact> tstCont = new List<Contact>();
        for(integer i = 0; i < 25; i++) {
            Contact c = new Contact(AccountId = a.Id,
                                    LastName = 'NotFirstName'+i);
            tstCont.add(c);
        }
        insert tstCont;

        Test.startTest();
        ContactBatch cont = new ContactBatch();
        Database.executeBatch(cont);
        Test.stopTest();
    }
}

Best Answer

You can modify your tests to call each method directly:

ContactBatch cb = New ContactBatch();

Database.QueryLocator ql = cb.start(null);
cb.execute(null,YOURLISTOFRECORDS);
cb.Finish(null);
Related Topic