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
Abhi MalikAbhi Malik 

Please Help Me To Write Test Class For This Trigger

********************trigger*****************

trigger WorkerStatusBefore on schnja__Worker_Status__c (before delete, before insert, before update) {
    
    if(Trigger.isInsert){
            TriggersWorkerStatus.handleBeforeInsert(Trigger.new);
    }
    else if(Trigger.isUpdate){
        TriggersWorkerStatus.handleBeforeUpdate(Trigger.oldMap,Trigger.newMap);
    }
    else if(trigger.isDelete){
        UtilWorkerStatus.checkAccessList(trigger.old);
    }  
}


********************UtilWorkerStatusClass*****************************
public with sharing class UtilWorkerStatus {
    
    public static Worker_Status__c createWorkerStatus(Id workerId, DateTime startDateTime, DateTime endDateTime, Id recordType){
        Worker_Status__c newWorkerStatus = generateWorkerStatus(workerId, startDateTime, endDateTime, recordType);
        insert newWorkerStatus;
        return newWorkerStatus;
    }
    public static Worker_Status__c generateWorkerStatus(Id workerId, DateTime startDateTime, DateTime endDateTime, Id recordType){
        return new Worker_Status__c(
            Worker__c = workerId, 
            Start_Date_Time__c = startDateTime, 
            End_Date_Time__c = endDateTime,
            RecordTypeId = recordType);
    }
    
    public static Worker_Status__c createDummyWorkerStatus(Id workerId, Id orgId){
        Worker_Status__c newWorkerStatus = generateDummyWorkerStatus(workerId, orgId);
        insert newWorkerStatus;
        return newWorkerStatus;
    }
    
    public static Worker_Status__c generateDummyWorkerStatus(Id workerId, Id orgId){
        if(orgId == null){
            orgId = UtilOrgLevel.createOrgLevel('Dummy', null).Id;
        }
        if(workerId == null){
            workerId = UtilWorker.createWorker('Dummy', 'Worker', orgId).Id;
        }
        return generateWorkerStatus(workerId, DateTime.now().addHours(1), DateTime.now().addHours(6), UtilGeneral.getRecordTypeId('schnja__Worker_Status__c', 'One-Time Availability'));
    }
    
    public static Map<Id,Boolean> checkAccessList (List<Worker_Status__c> record){
        Map <Id, boolean> accessMap = new Map <Id, boolean> ();
        //Check to see if the current user is an Availability Admin, If so return true for all Ids
        if(UtilGeneral.avilabilityPermissions.Availability_Admin__c){
            //Iterate through records, add them to accessMap with True and return it
            for(Worker_Status__c accessRecord:record){
                accessMap.put(accessRecord.Id,True);
            }
            return accessMap;
        }
        //Build a list of Ids of the scheduled Workerss
        system.debug(record);
        List <Id> workerIDs = new List <Id> ();
        for (Worker_Status__c accessRecord:record){
            workerIDs.add(accessRecord.Worker__c);
        }

        // Query to get the contact record of the scheduled workers
        Map <Id, Worker__c> currentWorker = new Map <Id,Worker__c> ([select Id, User_Record__c, Reports_To__r.User_Record__c from Worker__c where Id in :workerIds]);
        Id currentUser = UserInfo.getUserId();
        Boolean managersCanEdit = UtilGeneral.defaultSettings.Managers_Can_Edit_Availability__c;

        // Iterate through records, check to see if the user has access to change that record.  Add the Id and true to accessMap if they have access, false if not
        for (Worker_Status__c accessRecord:record){ 
            if(currentUser == currentWorker.get(accessRecord.Worker__c).User_Record__c || managersCanEdit && currentWorker.get(accessRecord.Worker__c).Reports_To__r.User_Record__c == currentUser){
                accessMap.put(accessRecord.Id,True);
            }else{
                accessMap.put(accessRecord.Id,False);
            }
        }
        return accessMap;
    }
    public static List<Worker_Status__c> generateNewInstances(Worker_Status__c recurring)
    {
        List<Worker_Status__c> newInstances = new List<Worker_Status__c>{};
        // Set the beginning Instance date to the start date of the 
        //  recurring or budget transaction
        DateTime currentStart = recurring.schnja__Start_Date_Time__c;
        DateTime currentEnd = recurring.schnja__End_Date_Time__c;
        
        // Determine the end date for the instance transactions
        // TODO:  Update this to look at the organization's Availability Settings
        Date finalDate = recurring.schnja__Repeat_Until__c == null ? (Date) recurring.schnja__Start_Date_Time__c.addYears(2) : recurring.schnja__Repeat_Until__c; 
        
        Id instanceRecordTypeId = UtilGeneral.getRecordTypeId('schnja__Worker_Status__c', 'Availability Instance');
        
        while(currentStart<=finalDate)
        {
            Worker_Status__c newStatus = UtilWorkerStatus.generateWorkerStatus(recurring.schnja__Worker__c, currentStart, currentEnd, instanceRecordTypeId);
            newStatus.Instance_Of__c = recurring.Id;
            newStatus.Description__c = recurring.Description__c;
            
            newInstances.add(newStatus);
            
            if(recurring.schnja__Recurrence_Interval__c == 'Days')
            {
                currentStart = currentStart.addDays(recurring.schnja__Recurs_Every__c.intValue());
                currentEnd = currentEnd.addDays(recurring.schnja__Recurs_Every__c.intValue());
            }
            else if(recurring.schnja__Recurrence_Interval__c == 'Weeks')
            {
                currentStart = currentStart.addDays(recurring.schnja__Recurs_Every__c.intValue() * 7);
                currentEnd = currentEnd.addDays(recurring.schnja__Recurs_Every__c.intValue() * 7);
            }
            else if(recurring.schnja__Recurrence_Interval__c == 'Months'){
                currentStart = currentStart.addMonths(recurring.schnja__Recurs_Every__c.intValue());
                currentEnd = currentEnd.addMonths(recurring.schnja__Recurs_Every__c.intValue());
            }
            else{
                currentStart = currentStart.addYears(recurring.schnja__Recurs_Every__c.intValue());
                currentEnd = currentEnd.addYears(recurring.schnja__Recurs_Every__c.intValue());
            }
        }
        
        return newInstances;
    }


********************TriggersWorkerStatusClass***********************


public class TriggersWorkerStatus {
    public static void handleAfterInsert(Map<Id, Worker_Status__c> triggerMap){
        //Get list of recurring Worker Statuses
        //system.debug(Schema.getGlobalDescribe().get('schnja__Worker_Status__c').getDescribe().getRecordtypeInfosByName());
        
        list <Worker_Status__c> recurringStatus = new list <Worker_Status__c>();
        Id recurringStatusID = UtilGeneral.getRecordTypeId('schnja__Worker_Status__c', 'Recurring Availability');
        for (Worker_Status__c newStatus: triggerMap.values()){
            if (newStatus.RecordTypeID == recurringStatusID) recurringStatus.add(newStatus);
        }
        //If the list isn't empty, iterate through list and pass them to generateNewInstances
        if (!recurringStatus.isEmpty()){
            list <Worker_Status__c> newInstances = new list <Worker_Status__c>();
            for(Worker_Status__c newRecurringStatus: recurringStatus){
                newInstances.addAll(UtilWorkerStatus.generateNewInstances(newRecurringStatus));
            }
            //Insert list of new Instance records if it is not empty
            if (!newInstances.isEmpty()) insert newInstances;
        }
    }
    public static void handleAfterUpdate(Map<Id, Worker_Status__c> beforeMap, Map<Id, Worker_Status__c> afterMap){
        //create blank list of Worker Statuses
        list <Id> busyStatus = new list <Id>();
        //iterate through list of updated records
        for (Worker_Status__c updatedRecord: afterMap.values()){
            //check to see if the status is canceled.
            if(updatedRecord.Status__c == 'Canceled'){
                //If the status is cancelled, check to see if the dates or times have changed
                if (updatedRecord.Start_Date_Time__c != beforeMap.get(updatedRecord.ID).Start_Date_Time__c || updatedRecord.End_Date_Time__c != beforeMap.get(updatedRecord.ID).End_Date_Time__c){
                    //If they have set the Worker Status to Busy and add them to the list of Worker statuses to update
                    busyStatus.add(updatedRecord.Id);
                }
            }    
        }
        
        //Update the changed statuses if the list isn't empty (and everything that goes with it)
        if (!busyStatus.isEmpty()){
            list <Worker_Status__c> updatedStatus = [SELECT Id, Status__c from Worker_Status__c where Id in :busyStatus];
            for (Worker_Status__c statusRecord : updatedStatus){
                statusRecord.Status__c = 'Busy';
            }
            update updatedStatus;
        }
    }
    public static void handleBeforeUpdate(Map<Id, Worker_Status__c> beforeMap, Map<Id, Worker_Status__c> afterMap){
        //Check access and attach errors to records that the user doesn't have permission to modify
        Map <Id,Boolean> accessMap = UtilWorkerStatus.checkAccessList(afterMap.Values());
        for(Worker_Status__c statusRecord:afterMap.Values()){
            if(!accessMap.get(statusRecord.Id)) statusRecord.addError('You have insufficient rights to update this Worker Status record.');
        }
    }
    public static void handleBeforeInsert(List <Worker_Status__c> beforeList){
        //Check access and attach errors to records that the user doesn't have permission to modify
        // system.debug(beforeList);
        Map <Id,Boolean> accessMap = UtilWorkerStatus.checkAccessList(beforeList);
        for(Worker_Status__c statusRecord:beforeList){
            if(!accessMap.get(statusRecord.Id)) statusRecord.addError('You have insufficient rights to update this Worker Status record.');
        }
    }
    
    public static void handleBeforeDelete(List <Worker_Status__c> AfterList){
        //Check access and attach errors to records that the user doesn't have permission to Delete
        Map <Id,Boolean> deletemap = UtilWorkerStatus.checkAccessList(AfterList);
        for(Worker_Status__c statusRecord:AfterList){
            if(!deletemap.get(statusRecord.Id)) statusRecord.addError('You have insufficient rights to Delete this Worker Status record.');
        }
    }
}