function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Iswarya SekarIswarya Sekar 

can anyone help me with the test class for batch class

global class UserDeactivateAlert_V1 implements Database.Batchable<SObject>
{         
    public String query = 'SELECT Name, Id, email, IsActive, lastlogindate, IsPortalEnabled from user where lastlogindate < LAST_N_DAYS:8 AND IsActive = true';      
    
    //public String query = 'select id, name, lastlogindate,IsPortalEnabled,email from user where id =\'0059E0000074xx4\'';
    global Database.querylocator start(Database.BatchableContext bc)
    {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<User> scope)
    {
        system.debug('The list of Users :'+scope);
        Date todayDate = date.today();
 
        Date deactivateInternalDt = date.today().addDays(-180);
        Date deactivatePartnerDt = date.today().addDays(-90);
        Date finalInternalDt = date.today().addDays(-178);
        Date finalPartnerDt = date.today().addDays(-88);
        Date initialDt = date.today().addDays(60);
        
        Map<String, Job_Schedulers__c> DoNotDeactivate = Job_Schedulers__c.getAll();
        system.debug('DoNotDeactivate '+DoNotDeactivate );
                
        system.Debug(deactivateInternalDt +'deactivateInternalDt ');
        system.Debug(deactivatePartnerDt +'deactivatePartnerDt ');
        system.Debug(finalInternalDt +'finalInternalDt ');
        system.Debug(finalPartnerDt +'finalPartnerDt ');
        system.Debug(initialDt +'initialDt');
        
        map<String,List<User>> MapofUsers = new map<String,List<User>>();
        Set<Id> deactivateUsers = new Set<Id>();
                
        for(User usr :scope){
         Date userDate = usr.lastlogindate.date();
         system.debug(userDate + 'userDate');
        
            if(userDate <= initialDt && !DoNotDeactivate.containskey(usr.Id)){
            system.debug(userDate+'userDate');
                if(userDate == initialDt){
                    system.debug(userDate+'userDate');
            system.debug(initialDt+'initialDt');
                    //initialAlertPartnerUsers
                    if(usr.IsPortalEnabled==true){
                        if(!MapofUsers.containsKey('Alert_Mail_for_Partner_User')){
                            MapofUsers.put('Alert_Mail_for_Partner_User', new List<User>{usr});
                        }else{
                            MapofUsers.get('Alert_Mail_for_Partner_User').add(usr);
                        }
                        system.debug(usr +'initialAlertPartnerUsers');
                    }else{
                        //initialAlertInternalUsers
                        if(!MapofUsers.containsKey('Alert_Mail_for_Internal_Users')){
                            MapofUsers.put('Alert_Mail_for_Internal_Users', new List<User>{usr});
                        }else{
                            MapofUsers.get('Alert_Mail_for_Internal_Users').add(usr);
                        }system.debug(usr +'initialAlertInternalUsers');
                    }
                }
                //finalAlertPartnerUsers
                else if(userDate == finalPartnerDt && usr.IsPortalEnabled==true){
                    if(!MapofUsers.containsKey('Deactivation_email_for_External_Users')){
                            MapofUsers.put('Deactivation_email_for_External_Users', new List<User>{usr});
                        }else{
                            MapofUsers.get('Deactivation_email_for_External_Users').add(usr);
                        }
                     system.debug(usr +'finalAlertPartnerUsers');   
                }
                //finalAlertInternalUsers
                else if(userDate == finalInternalDt && usr.IsPortalEnabled==false){
                    if(!MapofUsers.containsKey('Deactivation_email_for_Internal_Users')){
                            MapofUsers.put('Deactivation_email_for_Internal_Users', new List<User>{usr});
                        }else{
                            MapofUsers.get('Deactivation_email_for_Internal_Users').add(usr);
                        }
                       system.debug(usr +'finalAlertInternalUsers'); 
                }
                else if(userDate <= deactivatePartnerDt && usr.IsPortalEnabled==true){
                    deactivateUsers.add(usr.Id);
                }  
                else if(userDate <= deactivateInternalDt && usr.IsPortalEnabled==false){
                    deactivateUsers.add(usr.Id);
                } 
            }    
        } 
        system.debug(deactivateUsers.size()+'deactivateUsers');    
        if(deactivateUsers.size()>0){
        UserAlertAndDeactivation_Handler.UserDeactivation(deactivateUsers);
        }
        system.debug(MapofUsers +'MapofUsers');
        if(MapofUsers.size()>0){
            UserAlertAndDeactivation_Handler.sendEmailToUsers(MapofUsers);
        }        
    }    
    global void finish(Database.BatchableContext bc)
    {  
    }  
}



public class UserAlertAndDeactivation_Handler { 
    
    public static void sendEmailToUsers(map<String, List<User>> MapofUsers){
        
        List<EmailTemplate> listEmailTemplate = [select Id,DeveloperName from EmailTemplate where DeveloperName IN : MapofUsers.keySet()];
        Map<string, Id> mapEmailTemplate = new Map<string, Id>();
       
        for(EmailTemplate et : listEmailTemplate){
            mapEmailTemplate.put(et.DeveloperName,et.Id);
        }
        
        List<Messaging.SingleEmailMessage> allMessages = New List<Messaging.SingleEmailMessage>();
        
        for(String tempName: MapofUsers.keyset()){
            List<User> userList= MapofUsers.get(tempName);
            for(User u: userList){
                Messaging.SingleEmailMessage m = new Messaging.SingleEmailMessage();
                m.setTemplateId(mapEmailTemplate.get(tempName));
                m.setTargetObjectId(u.Id);
                m.saveAsActivity = false;
                allMessages.add(m);
            }
        }     
        system.debug(allMessages);
        //Messaging.sendEmail(allMessages); 
    }
    
    public static void UserDeactivation(Set<Id> deactivateUsers)
    {
        List<user> deactivatingUserList= new List<user>();
        for(User us : [select Id, IsActive from User where Id IN : deactivateUsers]){
            us.isActive=false;
            deactivatingUserList.add(us);
        }
        system.debug(deactivatingUserList+'deactivatingUserList');
        //database.update(deactivatingUserList);
    }
}
SUNDARAVEL JSUNDARAVEL J
Hello  Iswarya Sekar ,

I faced a same situation where I will be sending the email to Lead owners if the particular record is not modified for 30 days.In this case there are only two options for writing the test class
1. Use static resource to load the records with past date as lastmodified and created date (For Changing the last modified date and created date you require two permissions. Even if we have those permission the dates can be changed through API) After loading the static resource use that static resource in Test.loadData method.

syntax:
List<sObject> someInstance = Test.loadData( schema.sobjectType,"Static resource name");
example :
List<Lead> leadRecords = Test.loadDate(Lead.sobjectType,'Test Records');

The above static resource must be of type .csv with UTF 8 or normal .csv

2 Another option is using JSON to Build the records and deserialize them to use it but it is not supported for bulk creation of records 

Hope this helps you 
Thanks !!

 
SUNDARAVEL JSUNDARAVEL J
@isTest 
public  class InactiveLeads_AC_Test { 
         @isTest static void testLoadData() {         
         List < sObject > ls = Test.loadData(Lead.sObjectType, 'testLeads'); 

         Lead leadRecord = (lead) ls[0];   
     
         System.assert(ls.size() == 1);
         String leadStatus = leadRecord.Status;       
         DateTime leadDate = leadRecord.CreatedDate;     
         System.debug('Lead Status: ' + leadStatus ); 
         System.debug('Lead Date: ' + leadDate);         
         leadRecord.status = 'New';         

         update leadRecord;         
         System.debug('Lead status: ' + leadRecord.status);     
    }
}

I have attached a sample code for your reference 
Iswarya SekarIswarya Sekar
This is my test class for batch class. but is covering only 60%.
@isTest(seeAllData=true)
public class Test_UserDeactivateAlert_V1 {    
    static testMethod Void Method1(){ 
        // user usr = [SELECT Name, Id, email, IsActive, lastlogindate, IsPortalEnabled from user where lastlogindate < LAST_N_DAYS:200 AND IsActive = true LIMIT 1];
        user usr = new user();
        usr.Username = 'test@sample.com';
        usr.FirstName='Testing';
        usr.LastName='User';        
        usr.Alias = 'firstusr';
        usr.IsActive=true;
        usr.TimeZoneSidKey = 'America/Los_Angeles';
        usr.LocaleSidKey = 'en_US';
        usr.EmailEncodingKey = 'UTF-8';
        usr.LanguageLocaleKey = 'en_US';
        usr.ProfileId = [SELECT Id FROM Profile WHERE Name LIKE 'partner%'].id;
        usr.Email='test2@gmail.com';
        try
        {
            insert usr;
        }
        catch(Exception e)
        {
            System.debug(e);
        } 
        
        Test.startTest(); 
        UserDeactivateAlert_V1 obj = new UserDeactivateAlert_V1();
       // ID batchprocessid = Database.executeBatch(obj);
        DataBase.executeBatch(obj); 
        Test.stopTest();
        
    }        
}