+ Start a Discussion
buggs sfdcbuggs sfdc 

test class on UserLogin Batch Class

HI,

Need help covering test class for below Apex Batch class,i really appreciate if someone respond me quickly.
Thanks In Advance!
 
global class UpdateBatch_Usr_login implements Database.Batchable<sObject> {
    String query;
    global Database.QueryLocator start(Database.BatchableContext BC) {

        query = 'SELECT Id, isActive, Status__c FROM User';

        return Database.getQueryLocator(query);

    }
    global void execute(Database.BatchableContext BC, List<User> scope) {    

        List<Id> usrLogLst = new List<Id>();

        for(UserLogin ul : [SELECT UserId, isFrozen from UserLogin where isFrozen = true and UserId IN: scope]){

           usrLogLst.add(ul.userid);
        }
        for(User usr : scope){

            if(usrLogLst.contains(usr.id)){

                usr.status__c = 'Frozen';
            }

            else{

                if(usr.isActive==true){

                    usr.status__c = 'Active';
                }

                else{
                    usr.status__c = 'Inactive';

                }

            }

        }

        update scope;
    }

    global void finish(Database.BatchableContext BC) {

    }
}

 
jigarshahjigarshah
Use the below test code. Only thing to ensure, is the production org has atleast one active Salesforce license available while this test class is running or else it will result in test code failures.
 
@isTest
private class TestUpdateBatch_Usr_login  {

   //Verify Frozen User
   public static testMethod void testFrozenUser() {

      Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
	  
      User testUser = new User(
		 Alias = 'newUser', Email='newuser@testorg.com',
         EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
         LocaleSidKey='en_US', ProfileId = p.Id,
         TimeZoneSidKey='America/Los_Angeles', 
		 UserName = 'newuser@testorg.com');

	  Database.SaveResult userInsertResult = Database.insert(testUser);
	  
	  test.startTest();
	  
	  User userToFreeze = [Select Id, Name, IsFrozen from User Where Id = :testUser.Id]
	  userToFreeze.IsFrozen = true;
	  
	  update userToFreeze;
	  database.executeBatch(new UpdateBatch_Usr_login());
	  
	  test.stopTest();
	  
	  User assertUser = [Select Id, UserName, Status__c 
						 From User Where UserName = :'newuser@testorg.com'][0];
	  
	  System.assertEquals('Frozen', assertUser.Status__c);
   }
   
   //Verify Active User
   public static testMethod void testActiveUser() {

      Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
	  
      User testUser = new User(
		 Alias = 'newUser', Email='newuser@testorg.com',
         EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
         LocaleSidKey='en_US', ProfileId = p.Id,
         TimeZoneSidKey='America/Los_Angeles', 
		 UserName = 'newuser@testorg.com');

	  Database.SaveResult userInsertResult = Database.insert(testUser);
	  
	  test.startTest();
	  
	  database.executeBatch(new UpdateBatch_Usr_login());
	  
	  test.stopTest();
	  
	  User assertUser = [Select Id, UserName, Status__c 
						 From User Where UserName = :'newuser@testorg.com'][0];
	  
	  System.assertEquals('Active', assertUser.Status__c);
   }
   
   //Verify Inactive User
   public static testMethod void testInActiveUser() {

      Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
	  
      User testUser = new User(
		 Alias = 'newUser', Email='newuser@testorg.com',
         EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
         LocaleSidKey='en_US', ProfileId = p.Id,
         TimeZoneSidKey='America/Los_Angeles', 
		 UserName = 'newuser@testorg.com',
		 IsActive = false);

	  Database.SaveResult userInsertResult = Database.insert(testUser);
	  
	  test.startTest();
	  
	  database.executeBatch(new UpdateBatch_Usr_login());
	  
	  test.stopTest();
	  
	  User assertUser = [Select Id, UserName, Status__c 
						 From User Where UserName = :'newuser@testorg.com'][0];
	  
	  System.assertEquals('Inactive', assertUser.Status__c);
   }
}

 
buggs sfdcbuggs sfdc
hey ,

Thanks for responding me quickly.
Here iam getting below errors,and on line 20 we are getting an error (IsFrozen is not valid),the reason we have IsFrozen  field in userlogin.
 
System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.<br>The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). : [Username]


 
buggs sfdcbuggs sfdc
Hey Jigarshah,

Some how i resolved the issue,but now iam seeing different error, i tried creating a list and checked with if(lst.size()>0) condition.
But still iam seeing the same error can u please check
 
Error Message	System.AssertException: Assertion Failed: Expected: Active, Actual: null
Stack Trace	Class.TestUpdateBatch_Usr_login.testActiveUser: line 56, column 1

 
jigarshahjigarshah
  • The first error "System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_USERNAME, Duplicate Username.<br>The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). : [Username]" occurs because Salesforce does not permit having 2 users with the same Username value. Hence the resolution for this would be to make the Username value unique by appending a unique number or to append a datetime value using DateTime.now().
 
  • The second error "Error Message System.AssertException: Assertion Failed: Expected: Active, Actual: null
    Stack Trace Class.TestUpdateBatch_Usr_login.testActiveUser: line 56, column 1
    that you encounter is because the following query at line # 54, 55 does not return a valid User record and hence the value for assertUser in the testActiveUser()  is null. Check if the Where clause is returning the expected User record.
Amit Chaudhary 8Amit Chaudhary 8
Update your Batch job like below
global class UpdateBatch_Usr_login implements Database.Batchable<sObject> {
    String query;
    global Database.QueryLocator start(Database.BatchableContext BC) {

        query = 'SELECT Id, isActive, Status__c FROM User';
        if(Test.isRunningTest()){
            String profileName = 'Standard User';
            query = 'SELECT Id, isActive, Status__c FROM User where profile.Name=:profileName ';
        }

        return Database.getQueryLocator(query);

    }
    global void execute(Database.BatchableContext BC, List<User> scope) {    

        List<Id> usrLogLst = new List<Id>();

        for(UserLogin ul : [SELECT UserId, isFrozen from UserLogin where isFrozen = true and UserId IN: scope]){

           usrLogLst.add(ul.userid);
        }
        for(User usr : scope){

            if(usrLogLst.contains(usr.id)){

                usr.status__c = 'Frozen';
            }

            else{

                if(usr.isActive==true){

                    usr.status__c = 'Active';
                }

                else{
                    usr.status__c = 'Inactive';

                }

            }

        }

        update scope;
    }

    global void finish(Database.BatchableContext BC) {

    }
}

Test Class like below
@isTest
private class TestUpdateBatch_Usr_login  {

   public static testMethod void testActiveUser() {

      Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
      
      User testUser = new User(
         Alias = 'newUser', Email='TestTest1234@testFrozenUser.com',
         EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
         LocaleSidKey='en_US', ProfileId = p.Id,
         TimeZoneSidKey='America/Los_Angeles', 
         UserName = 'TestTest1234@testFrozenUser.com');

      Database.SaveResult userInsertResult = Database.insert(testUser);
      
      test.startTest();

        
      database.executeBatch(new UpdateBatch_Usr_login());
      
      test.stopTest();
      
      User assertUser = [Select Id, UserName, Status__c 
                         From User Where id= :testUser.id][0];
      
      System.assertEquals('Active', assertUser.Status__c);
   }
   public static testMethod void testInActiveUser() {

      Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
      
      User testUser = new User(
         Alias = 'newUser', Email='TestTest1234@testFrozenUser.com',
         EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
         LocaleSidKey='en_US', ProfileId = p.Id,
         TimeZoneSidKey='America/Los_Angeles', 
         UserName = 'TestTest1234@testFrozenUser.com');

      Database.SaveResult userInsertResult = Database.insert(testUser);
      
      test.startTest();
        testUser.isActive=false;
        update testUser;
        
      database.executeBatch(new UpdateBatch_Usr_login());
      
      test.stopTest();
      
      User assertUser = [Select Id, UserName, Status__c 
                         From User Where id= :testUser.id][0];
      
      System.assertEquals('Inactive', assertUser.Status__c);
   }

}

With Above changes you will get 88% (16/18).

You can not create userLogin record in your test class. and isFrozen  is available on UserLogin object not on user object

 
buggs sfdcbuggs sfdc
Hi Amit,

can you please look into it,iam getting the below Error.
Error Message	System.AssertException: Assertion Failed: Expected: Inactive, Actual: Active
Stack Trace	Class.TestUpdateBatch_Usr_login.testInActiveUser: line 53, column 1



 
Amit Chaudhary 8Amit Chaudhary 8
I tested above code in my developer org which is working fine. Do you have any workflow or Trigger on User object to make user Active ?

I hope you also added below line in your batch job
query = 'SELECT Id, isActive, Status__c FROM User';
        if(Test.isRunningTest()){
            String profileName = 'Standard User';
            query = 'SELECT Id, isActive, Status__c FROM User where profile.Name=:profileName ';
        }

 
buggs sfdcbuggs sfdc
Yes, i  changed the code as above,and their are no triggers or WF on User,but still iam seeing the same error.
Please check and let me know where iam lagging,i really appreciate your time for helping me on resolving it.
Vinay Kumar SattaruVinay Kumar Sattaru
Hi SFDC Folks,

For my Batch apex

global class Communityuserinactivation implements Database.stateful,Database.Batchable<sObject> 
{
     public List<User> userrecordsprocessed= new List<User>();
    
     global Database.QueryLocator start(Database.BatchableContext BC)
     {
         String query='Select id,LastLoginDate,username,CommunityNickname,isActive,FederationIdentifier from user where isActive=True AND Profile.name=\'System Administrator\' LIMIT 10';
           System.debug('+++query'+query);
         return database.getQueryLocator(query);      
     }
    
     global void execute(Database.BatchableContext BC, List<user> scope)
     {
         System.debug('++++scope'+scope);
            // userrecordsprocessed=scope;
         List<User> lisuser= new List<User>();
         for(user us:scope)
         {
             String usrname=us.username;
             String CmmunityNickname=us.CommunityNickname;
             Datetime dt=us.LastLoginDate;
             datetime dt2= System.now();
             integer intDays =dt.Date().daysBetween(dt2.Date());
            
             if(intDays>=10)
             {
                 if(usrname.length()>34)
                 {
                     usrname=usrname.substring(0,usrname.length()-7);
                 }              
              
                 if(CmmunityNickname.length()>34)
                 {
                     CmmunityNickname=CmmunityNickname.substring(0,usrname.length()-7);
                 }
             us.Username=usrname+'.old'+String.valueOf(Math.random()).substring(2, 4);
             us.CommunityNickname=CmmunityNickname+'.old'+String.valueOf(Math.random()).substring(2, 4);
             us.FederationIdentifier='';
             //us.CCO_ID__c='';
             us.IsActive=False;
             userrecordsprocessed.add(us);
             System.debug('++++lisuser'+lisuser);
          }
      }
          
      update userrecordsprocessed;
    
     }
    
    global void finish(Database.BatchableContext BC)
    {
        string csvHeader = 'User ID, UserName,Lastlogindate,CommunityNickname,FederationIdentifier,IsActive \n';
        string mainContent = csvHeader;
        
        for(User us:userrecordsprocessed)
        {
            string recordString = us.id+','+us.Username+','+us.LastLoginDate+','+us.CommunityNickname+','+us.FederationIdentifier+','+us.IsActive+'\n';
            mainContent+=recordString;
        } 
        
        Messaging.EmailFileAttachment csvAttcmnt = new Messaging.EmailFileAttachment ();
        blob csvBlob = Blob.valueOf(mainContent);
        string csvname= 'Inactiveusers.csv';
        csvAttcmnt.setFileName (csvname);
        csvAttcmnt.setBody (csvBlob);
        Messaging.SingleEmailMessage singEmail = new Messaging.SingleEmailMessage ();
        String [] toAddresses = new list<string> {'vsattaru@cisco.com'};
        singEmail.setToAddresses (toAddresses);
        String subject ='Inactiveuser list';
        singEmail.setSubject (subject);
        singEmail.setPlainTextBody ('users not logged in last 6 months');
        singEmail.setFileAttachments (new Messaging.EmailFileAttachment []{csvAttcmnt});
        Messaging.SendEmailResult [] r = Messaging.sendEmail (new Messaging.SingleEmailMessage [] {singEmail});
    }
}


I am writing the below Test Class but unable to get Code Coverage, it was stuck at 72% and not getting executed. Could you please help!!!

Here is my test class

@isTest
private class testclassbatchapex 
{
    public static testmethod void testquery()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        User testUser = new User(Alias = 'newUser', Email='newusser@testorg.com', 
        EmailEncodingKey='UTF-8', LastName='Testing', LocaleSidKey='en_US', LanguageLocaleKey='en_US', TimeZoneSidKey='America/Los_Angeles',
        ProfileId = p.Id, UserName = 'newusser@testorg.com');
 
        Database.SaveResult userInsertResult = Database.insert(testUser);
       
        test.startTest();
       
        User Usr = [Select Id, Name, isActive from User Where Id = :testUser.Id];
        Usr.isActive = true;
       
        update Usr;
        database.executeBatch(new Communityuserinactivation());
        
        test.stopTest();
       
        User assertUser = [Select Id, UserName From User Where UserName = :'varshas@accenture.com'];
        //system.assertEquals('true', 'false');
        //System.assertEquals('true', assertUser.IsActive);
     }
    
        testmethod static void Communityuserinactivationnn() 
        {
            Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
       
            User testUser = new User(
             Alias = 'newUser', Email='fastusserr@testorg.com',
             EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
             LocaleSidKey='en_US', ProfileId = p.Id,
             TimeZoneSidKey='America/Los_Angeles',
             UserName = 'fastusserr@testorg.com');
 
              Database.SaveResult userInsertResult = Database.insert(testUser);
       
              test.startTest();

             database.executeBatch(new Communityuserinactivation());
       
              test.stopTest();
       
              User assertUser = [Select Id, UserName From User Where UserName = :'fastusserr@testorg.com'][0];
       
              //System.assertEquals('Active', assertUser.Status__c);
           }
    
           testmethod static void testme()  
           {
               Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
      
             User testUser = new User(
           Alias = 'newUser', Email='fastuser@testorg.com',
           EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
           LocaleSidKey='en_US', ProfileId = p.Id,
           TimeZoneSidKey='America/Los_Angeles',
           UserName = 'fastuser@testorg.com',
           IsActive = false);

           Database.SaveResult userInsertResult = Database.insert(testUser);
       
           test.startTest();
       
           database.executeBatch(new Communityuserinactivation());
       
           test.stopTest();
      
           User assertUser = [Select Id, UserName From User Where UserName = :'fastuser@testorg.com'][0];
       
           //System.assertEquals('False', assertUser.isActive);
   }
}
Christian Schwabe 8Christian Schwabe 8
Hello guys,

I have the same requirement and i want to show you my approach, which will work also.
My solution works until three licences are active on runnning org.
I emulate UserLogin into a custom inner class and use this for test purposes. Feel free to criticize and comment this solution. I would be very happy about that. 


Below my scheduled batchjob:
/**
* @purpose: BatchJob to evaluate if users are currently locked, 
*           frozen or green (=active) and update a flag on User.
*
* @author:  Christian Schwabe
*
* @history:
* version                   | author                                    | changes
* ====================================================================================
* 0.1 29.01.2020            | Christian.Schwabe@colliers.com            | Inital version.
*/


global with sharing class EvaluateLockedUserBatch implements Schedulable{
    global void execute(SchedulableContext schedulableContext) {
        List<User> toBeUpdatedUser = new List<User>();

        //Retrieve all active users.
        Map<Id, User> mapOfActiveUserById = new Map<Id, User>([SELECT
                                                                    Id, Status__c 
                                                                FROM
                                                                    User 
                                                                WHERE
                                                                    IsActive = true AND
                                                                    UserType = 'Standard'
                                                                ]);

        List<Object> listOfGenericUserLogin = new List<Object>();
        //If no running test: select from existing data
        if(Test.isRunningTest() == false){
            listOfGenericUserLogin = [SELECT
                                            UserId, IsPasswordLocked, IsFrozen 
                                        FROM
                                            UserLogin 
                                        WHERE
                                            UserId = :mapOfActiveUserById.keySet()
                                    ];
        } else {//If running test: use a wrapper class (CustomUserLogin)
            User frozenUser = mapOfActiveUserById.values().get(0);
            CustomUserLogin frozenUserLogin = new CustomUserLogin(true, false, frozenUser.Id);
            listOfGenericUserLogin.add(frozenUserLogin);

            User passwordLockedUser = mapOfActiveUserById.values().get(1);
            CustomUserLogin passwordLockedUserLogin = new CustomUserLogin(false, true, passwordLockedUser.Id);
            listOfGenericUserLogin.add(passwordLockedUserLogin);
        
            User user = mapOfActiveUserById.values().get(2);
            CustomUserLogin userLogin = new CustomUserLogin(false, false, user.Id);
            listOfGenericUserLogin.add(userLogin);
        }

        //Check UserLogin to evaluate if a user is frozen, locked or active.
        for(Object genericUserLogin : listOfGenericUserLogin){
            Id userId;
            Boolean isFrozen;
            Boolean isPasswordLocked;

            if(Test.isRunningTest() == false){
                UserLogin userLogin = (UserLogin) genericUserLogin;
                userId = userLogin.Id;
                isFrozen = userLogin.IsFrozen;
                isPasswordLocked = userLogin.IsPasswordLocked;
            } else {
                CustomUserLogin customUserLogin = (CustomUserLogin) genericUserLogin;
                userId = customUserLogin.userId;
                isFrozen = customUserLogin.isFrozen;
                isPasswordLocked = customUserLogin.isPasswordLocked;
            }

            User user                   = mapOfActiveUserById.get(userId);
            String oldStatus            = '' + user.Status__c;
            Boolean statusHasChanged    = false;

            if(isFrozen){
                user.Status__c = 'Frozen';
            } else if(isPasswordLocked){
                user.Status__c = 'Locked';
            } else {
                user.Status__c = 'Green';
            }

            statusHasChanged = this.hasChanged(oldStatus, user.Status__c);

            if(statusHasChanged == true){//Apply update on records, only if status has changed to minimize dmls.
                toBeUpdatedUser.add(user);
            }
        }

        List <Database.SaveResult> saveResult = Database.update(toBeUpdatedUser, false);
        System.debug('>>>saveResult: ' + saveResult);

        this.reschedule(schedulableContext);
    }

    /**
    * Check if status has changed.
    *
    * @param oldValue - String: source string.
    * @param newValue - String: to be compared string.
    *
    * @return Boolean - If comparison is not equals -> true - Otherwise: false
    */
    private Boolean hasChanged(String oldValue, String newValue){
        return ! oldValue.equalsIgnoreCase(newValue);
    }

    private void reschedule(SchedulableContext schedulableContext){
        System.debug('>>>Abort job, rescheduling');
        Id jobId = schedulableContext.getTriggerId();
        System.abortJob(jobId);

        //Reschedule Job after 15 minutes.
        Datetime dateTimee  = System.now().addMinutes(15);
        String day          = String.valueOf(dateTimee.day());
        String month        = String.valueOf(dateTimee.month());
        String hour         = String.valueOf(dateTimee.hour());
        String minute       = String.valueOf(dateTimee.minute());
        
        String strSchedule = '0 ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ?';
        System.schedule('>>>EvaluateLockedUserBatch', strSchedule, new EvaluateLockedUserBatch());
        System.debug('>>Scheduled new EvaluateLockedUserBatch() for time: ' + strSchedule);
    }

    private class CustomUserLogin{
        private Boolean isFrozen;
        private Boolean isPasswordLocked;
        private Id userId;

        public CustomUserLogin(Boolean isFrozen, Boolean isPasswordLocked, Id userId){
            this.isFrozen = isFrozen;
            this.isPasswordLocked = isPasswordLocked;
            this.userId = userId;
        }
    }
}

Below my testclass:
@isTest
private class EvaluateLockedUserBatchTest {

    @isTest
    private static void testFrozenUser(){
        List<User> listOfFrozenUser = new List<User>([SELECT Id, Status__c FROM User WHERE Status__c = 'Frozen']);
        Integer expected = 0;
        Integer actual = listOfFrozenUser.size();
        System.assertEquals(expected, actual, 'No user should be frozen.');

        /*
        * To test a schedulable, schedule a run in your test method using System.schedule(),
        * and wrap that call in Test.startTest() and Test.stopTest(). 
        * This will ensure that the scheduled job is finished when Test.stopTest() completes and the next line of code runs. 
        */ 
        Test.startTest();
            System.runAs(getUser()){
                Id jobId = executeBatchJob();
            }
        Test.stopTest();

        listOfFrozenUser = new List<User>([SELECT Id, Status__c FROM User WHERE Status__c = 'Frozen']);
        expected = 1;
        actual = listOfFrozenUser.size();
        System.assertEquals(expected, actual, 'Exactly one user should be frozen.');
    }

    @isTest
    private static void testLockedUser(){
        List<User> listOfFrozenUser = new List<User>([SELECT Id, Status__c FROM User WHERE Status__c = 'Locked']);
        Integer expected = 0;
        Integer actual = listOfFrozenUser.size();
        System.assertEquals(expected, actual, 'No user should be locked.');

        /*
        * To test a schedulable, schedule a run in your test method using System.schedule(),
        * and wrap that call in Test.startTest() and Test.stopTest(). 
        * This will ensure that the scheduled job is finished when Test.stopTest() completes and the next line of code runs. 
        */ 
        Test.startTest();
            System.runAs(getUser()){
                Id jobId = executeBatchJob();
            }
        Test.stopTest();

        listOfFrozenUser = new List<User>([SELECT Id, Status__c FROM User WHERE Status__c = 'Locked']);
        expected = 1;
        actual = listOfFrozenUser.size();
        System.assertEquals(expected, actual, 'Exactly one user should be locked.');
    }

    @isTest
    private static void testActiveUser(){
        List<User> listOfFrozenUser = new List<User>([SELECT Id, Status__c FROM User WHERE Status__c = 'Green']);
        Integer expected = 0;
        Integer actual = listOfFrozenUser.size();
        System.assertEquals(expected, actual, 'No user should be active.');

        /*
        * To test a schedulable, schedule a run in your test method using System.schedule(),
        * and wrap that call in Test.startTest() and Test.stopTest(). 
        * This will ensure that the scheduled job is finished when Test.stopTest() completes and the next line of code runs. 
        */ 
        Test.startTest();
            System.runAs(getUser()){
                Id jobId = executeBatchJob();
            }
        Test.stopTest();

        listOfFrozenUser = new List<User>([SELECT Id, Status__c FROM User WHERE Status__c = 'Green']);
        expected = 1;
        actual = listOfFrozenUser.size();
        System.assertEquals(expected, actual, 'Exactly one user should be active.');
    }

    private static User getUser(){
        User user = new User();
        user.LastName           = 'Heinz';
        user.Alias              = 'H1';
        user.Email              = 'H1@abc.de';
        user.Username           = user.Email;
        user.CommunityNickname  = 'Crazy ' + user.LastName;
        user.ProfileId          = getSystemAdministratorProfile().Id;
        user.EmailEncodingKey   = 'UTF-8'; 
        user.LanguageLocaleKey  = 'en_US';
        user.LocaleSidKey       = 'en_US';
        user.TimeZoneSidKey     = 'America/Los_Angeles';
        return user;
    }

    private static Profile getSystemAdministratorProfile(){
        List<String> listOfProfileName = new List<String>{ 'Systemadministrator', 'System Administrator' };
        return [SELECT Id FROM Profile WHERE Name IN :listOfProfileName LIMIT 1];
    }

    private static Id executeBatchJob(){
        //Reschedule Job after 15 minutes.
        Datetime dateTimee  = System.now().addMinutes(15);
        String day          = string.valueOf(dateTimee.day());
        String month        = string.valueOf(dateTimee.month());
        String hour         = string.valueOf(dateTimee.hour());
        String minute       = string.valueOf(dateTimee.minute());
        
        String schedule = '0 ' + minute + ' ' + hour + ' ' + day + ' ' + month + ' ?';
        Id jobId = System.schedule('>>>EvaluateLockedUserBatch', schedule, new EvaluateLockedUserBatch());

        return jobId;
    }
}