3

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();
    }
}
2

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);
  • Thanks @Eric. It's working. Is this the only best way to handle in these situations? – Seesh Nov 26 '14 at 3:42
  • @In this situation you had no choice as the record type was always set due to having default record types for the user profiles. With that said, why do you need the batch at all?? I am assuming it is a one time data run? – Eric Nov 26 '14 at 5:15
  • Yes. You are right. There are default recordtypes for profiles. But there are few which has no recordtypes so this batch is to run and explicitly assign the recordtype for those. Thank you. – Seesh Nov 26 '14 at 5:23

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.