Batch Class Example
Batch Class Example
=======
global class MyBatchClass implements Database.Batchable<sObject> {
global (Database.QueryLocator | Iterable<sObject>)
start(Database.BatchableContextbc) {
// collect the batches of records or objects to be passed to execute
}
global void execute(Database.BatchableContextbc, List<P> records){
// process each batch of records
}
global void finish(Database.BatchableContextbc){
// execute any post-processing operations
}
}
Contact which does not have any Account associated with it, should not be updated.
Batch Class
===========
// Getting all the contacts having some accountId populated using Query in
start() method
global Database.QueryLocator start(Database.BatchableContext bc) {
String query = 'Select Id, Account.Name, Title, Description,
Account.Description From Contact Where AccountId != null';
return Database.getQueryLocator(query);
}
Test Class
==========
Create Accounts (with some description) and Contacts associated with the Account
(without blank description).
Execute the batch Apex and verify that the Contacts Description should get updated
with some value.
@isTest
private class UpdateContactDescriptionTest {
@testSetup
static void dataSetup() {
// Insert Contacts with some description
List<Account> listOfAccounts = new List<Account>();
for(Integer i=0; i<10; i++) {
listOfAccounts.add(new Account(Name = 'TestAcc'+i,
Description = 'Account'+i + ' for Testing
Batch Apex'));
}
insert listOfAccounts;
@isTest
static void testMethod_ContactsWithAccounts() {
// Verify that description is empty for all the contacts before the batch
class is executed
List<Contact> contactsBeforeUpdation = [Select Id, Description From
Contact];
for(COntact con : contactsBeforeUpdation) {
System.assert(con.Description == null, 'Description should not be
empty');
}
Test.startTest();
UpdateContactDescription batchClass = new UpdateContactDescription();
Database.executeBatch(batchClass, 100);
Test.stopTest();
// Assert that description should not be updated and remain empty for
Contacts with no Account
List<Contact> contactsAfterUpdation_noAcc = [Select Id, Description,
Account.Name From Contact Where AccountId = null];
for(Contact con : contactsAfterUpdation_noAcc) {
System.assert(con.Description == null, 'Description should not be
empty');
}
}
}