I have a Batchable Apex class that queries against an external object in the QueryLocator. I need to be able to write a test against the batch apex class to achieve coverage. I've looked this answer and link which uses the concept of using a method to get query results, but does not use a queryLocator, which I need for the batchable class.
My existing sample POC code works fine when executed from anonymous apex, but I can't seem to get test coverage going.
global class BatchableLoadPersonsPersisted implements Database.Batchable<SObject> {
global BatchableLoadPersonsPersisted() {
}
/**
* @description gets invoked when the batch job starts
* @param context contains the job ID
* @returns the record set as a QueryLocator object that will be batched for execution
*/
global Database.QueryLocator start(Database.BatchableContext context) {
return Database.getQueryLocator('SELECT DATEBIRTH__c,DisplayUrl,ExternalId,FIRSTNAME__c,Id,LASTNAME__c,PERSNBR__c,SPOUSEPERSNBR__c FROM Persons__x');
}
/**
* @description gets invoked when the batch job executes and operates on one batch of records. Contains or calls the main execution logic for the batch job.
* @param context contains the job ID
* @param scope contains the batch of records to process.
*/
global void execute(Database.BatchableContext context, List<Persons__x> scope) {
List<PersistedPerson__c> persistedPersonsList = new List<PersistedPerson__c>();
for(Persons__x personx : scope)
{
PersistedPerson__c persistPerson = new PersistedPerson__c();
persistPerson.LASTNAME__c = personx.LASTNAME__c;
persistPerson.FIRSTNAME__c = personx.FIRSTNAME__c;
persistPerson.DATEBIRTH__c = personx.DATEBIRTH__c;
persistPerson.PERSONNUMBER__c = personx.PERSNBR__c;
persistedPersonsList.add(persistPerson);
}
upsert persistedPersonsList;
}
/**
* @description gets invoked when the batch job finishes. Place any clean up code in this method.
* @param context contains the job ID
*/
global void finish(Database.BatchableContext context) {
}
}
@isTest
private class BatchableLoadPersonsTests {
static testmethod void test() {
// Create test persons to be upserted
// by the batch job.
Test.startTest();
Persons__x[] persList = new List<Persons__x>();
Persons__x person = new Persons__x();
person.PERSNBR__c = 1;
person.LASTNAME__c = 'test';
person.DATEBIRTH__c = Date.newInstance(1960, 2, 17);
persList.add(person);
Database.insertImmediate(persList);
BatchableLoadPersonsPersisted batchLoad = new BatchableLoadPersonsPersisted();
batchLoad.start(null);
batchLoad.execute(null, persList);
batchLoad.finish(null);
//Database.executeBatch(batchLoad);
Test.stopTest();
// Verify persons updated
PersistedPerson__c[] accUpdatedList = [SELECT Id, LASTNAME__c, FIRSTNAME__c, PERSONNUMBER__c FROM PersistedPerson__c];
System.assert(!accUpdatedList.isEmpty());
}
}