Test Class:
@isTest
private class UsersFreeze_batch_Test{
static final String COMP = 'HID Global';
static final list<Countries__c> COUNTRIES = new list<Countries__c>([SELECT Name, Country__c, Region__c, Territory__c FROM Countries__c]);
static final list<States__c> STATES = new list<States__c>([SELECT Name, State__c, Region__c, Territory__c FROM States__c]);
static User u;
static {
Profile p = [
SELECT
Id
FROM
Profile
WHERE
Name = 'HID Sales User - IAM'
];
u = new User(
Alias = 'u1',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Testing',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
Country = 'United States',
CountryCode = 'US',
TimeZoneSidKey = 'America/Los_Angeles',
Username = '[email protected]',
Frozen__c = true
);
insert u;
}
static User u1;
static {
Profile p = [
SELECT
Id
FROM
Profile
WHERE
Name = 'HID Sales User - IAM'
];
u1 = new User(
Alias = 'u2',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Testing1',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
Country = 'United States',
CountryCode = 'US',
TimeZoneSidKey = 'America/Los_Angeles',
Username = '[email protected]',
Frozen__c = true
);
insert u1;
}
static testMethod void testBatch(){
test.startTest();
UsersUnFreeze_batch obj01 = new UsersUnFreeze_batch();
Database.executeBatch(obj01,1);
test.stopTest();
}
}
Apex Class:::::
global class UsersFreeze_batch implements Database.Batchable<SObject>, Database.AllowsCallouts {
// "Start" runs when the class in instanciated
global Database.QueryLocator start(Database.BatchableContext bcMain) {
if(test.IsRunningTest()){
return Database.getQueryLocator([select isFrozen,userId,id from UserLogin where isFrozen =:false limit 1]);
}
return Database.getQueryLocator([select isFrozen,userId,id from UserLogin where isFrozen =:false]);
}
public void FreezeUsers(List<UserLogin> lstUserData){
if(Label.Freeze_Escape_Profiles != null){
List<String> escapeProfiles = Label.Freeze_Escape_Profiles.split(',');
set<String> setEscapeProfiles = new set<string>();
setEscapeProfiles.addall(escapeProfiles);
if(!lstUserData.IsEmpty()){
List<UserLogin> recordsToProcess = new List<UserLogin>();
List<User> usersToUpdate = new List<User>();
set<Id> userIds = new set<Id>();
for(UserLogin ul:lstUserData){
userIds.add(ul.userId);
}
Map<Id,User> mapUsers = new Map<Id,User>([select id,name from user where Profile.Name Not In:setEscapeProfiles and Id In:userIds and IsActive=:true]);
for(UserLogin uls:lstUserData){
if(mapUsers.containsKey(uls.UserId)){
uls.IsFrozen = true;
recordsToProcess.add(uls);
user u = new user();
u.Id = uls.UserId;
u.Frozen__c = true;
usersToUpdate.add(u);
}
}
if(!usersToUpdate.IsEmpty()){
update usersToUpdate;
}
if(!recordsToProcess.IsEmpty()){
update recordsToProcess;
}
}
}
}
global void execute(Database.BatchableContext bcMain, List<SObject> lstBatchRecords)
{
FreezeUsers(lstBatchRecords);
}
// Finish the Batch Job
global void finish(Database.BatchableContext BC) {
List<AsyncApexJob> lsta = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
TotalJobItems, CreatedBy.Email, ExtendedStatus
from AsyncApexJob where Status =: 'Failed'];
if(!lsta.IsEmpty()){
AsyncApexJob a = lsta[0];
string plainbody = 'The batch Apex job processed ' + a.TotalJobItems+' batches with '+a.NumberOfErrors+ ' failures. ExtendedStatus: ' + a.ExtendedStatus;
sendEmai(a.Status,a.CreatedBy.Email,'Users Freeze Status: ',plainbody );
}else{
string plainbody = 'All the Users are Successfully Freezed, except System Admins and HID Integrations';
sendEmai('Success',userinfo.getuserEmail(),'Users Freeze Status: ',plainbody );
}
}
global void sendEmai(string status,string email,string subject,string plainbody ){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// Send the email to the job submitter
String[] toAddresses = new String[] {email};
mail.setToAddresses(toAddresses);
mail.setSenderDisplayName('Batch Processing');
mail.setSubject(subject+' ' + status);
mail.setPlainTextBody(plainbody);
// Add your attachment to the email.
if(!test.IsRunningTest()) {
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}
}