Use Case:

(Database.Stateful and Outbound functionality Use)

Create a batch class which would:

  1. Update all the account records owner to some new owner. (Example, Previous owner – abc@riteshgupta2492.com, New owner – xyz@riteshgupta2492.com)

  2. AND send an email to new owner mentioning total number of account records updated.

public class OwnersUpdateForAccountBatch implements Database.Batchable<sObject>, Database.Stateful {
// Create an integer which would keep track of the total number of accounts which have updated
public Integer numberOfAccountsProcessed=0;
private String oldUserId;
private String newUserId;
// Constructor which takes the argument as UserIds.
// oldUserId: Id of the User/AccountOwner which needs to be changed for accounts
// newUserId: Id of the User/AccountOwner to which accounts need to be updated
public OwnersUpdateForAccountBatch(String oldUserId, String newUserId) {
this.oldUserId = oldUserId;
this.newUserId = newUserId;
}
// Start method which would query all the accounts for oldUserId
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('Select Id From Account Where OwnerId= \'' + oldUserId + '\'');
}
// Update operation on AccountOwner/OwnerId field for all the queried accounts
public void execute(Database.BatchableContext bc, List<Account> listOfAccounts) {
for(Account acc : listOfAccounts) {
acc.OwnerId = newUserId;
numberOfAccountsProcessed++;
}
update listOfAccounts;
}
// Send email to the new user
public void finish(Database.BatchableContext bc) {
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new List<String> {newUserId});
email.setSubject('Total Accounts Updated');
email.setPlainTextBody('Below is the total number of Accounts whose new Owner is you:\n' + numberOfAccountsProcessed);
Messaging.sendEmail(new List<Messaging.SingleEmailMessage> {email});
}
}

Test Class:

1. Create two accounts, 1 with Admin User and 1 with new Standard User.
2. Treat Admin user as Old User and Standard User as New User which means that after executing the batch class,
Owner of the admin account should get updated to Standard User.

/**
* Test Class to create a new User
*/
@isTest
public class TestUserUtil {
public static User createUser(String fName, String lName, String alias, Profile profile) {
User usr = new User(LastName = lName,
FirstName = fName,
Alias = alias,
Email = fName + '.' + lName + '@apexstepbystep.com',
Username = 'test.user444@apexstepbystep.com',
ProfileId = profile.id,
TimeZoneSidKey = 'GMT',
LanguageLocaleKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LocaleSidKey = 'en_US'
);
return usr;
}
}


/**
* 1. Create two accounts, 1 with Admin User and 1 with new Standard User.
* 2. Treat Admin user as Old User and Standard User as New User which means that after executing the batch class,
*  Owner of the admin account should get updated to Standard User.
*/
@isTest
private class OwnersUpdateForAccountBatchTest {
@isTest
static void testM() {
Account adminAcc = new Account(Name='AdminAccount');
insert adminAcc;
Profile standardProfile = [Select Id From Profile Where Name = 'Standard User'];
User newUser = TestUserUtil.createUser('Test', 'User', 'tusr', standardProfile);
System.runAs(newUser) {
Account standAcc = new Account(Name='StandardAccount');
insert standAcc;
}
String oldUserId = UserInfo.getUserId();
// Assert that both the accounts were inserted and
// Owner of AdminAccount should be System Administrator user (oldUser) and
// Owner of Standard Account should be Standard User
List<Account> accountsBeforeBatchExecution = [Select Id, Name, OwnerId From Account];
System.assertEquals(2, accountsBeforeBatchExecution.size(), 'Accounts were not inserted.');
for(Account acc: accountsBeforeBatchExecution) {
if(acc.Name == 'AdminAccount') {
System.assertEquals(oldUserId, acc.OwnerId, 'Owner ids do not match');
}
if(acc.Name == 'StandardAccount') {
System.assertEquals(newUser.Id, acc.OwnerId, 'Owner ids do not match');
}
}
Test.startTest();
    Database.executeBatch(new OwnersUpdateForAccountBatch(oldUserId, newUser.Id));
Test.stopTest();
// Verify that Owner of AdminAccount should be updated as Standard User and
// Owner of StandardAccount should remain as Standard User
List<Account> accountsAfterBatchExecution = [Select Id, Name, OwnerId From Account];
System.assertEquals(2, accountsAfterBatchExecution.size(), 'Incorrect number of Accounts');
for(Account acc: accountsAfterBatchExecution) {
System.assertEquals(newUser.Id, acc.OwnerId, 'Owner ids do not match');
}
}
}
Code Coverage: 100%
Like it ? Share : Do Nothing

Leave a Reply