I've been going nuts over this. Nothing in my IF loop is firing through my test class and I cannot figure out why. I have done a lot of reading online and it appears that I am doing things correctly but it still hasn't solved my code coverage. This is the last line that runs:
If (isWithin == True){
after that I can't get anything to run within that IF loop, I have reversed the logic and it still doesn't run. I feel like I will kick myself when someone points it out but here is my code:
trigger caseCreatedDurringBusinessHours on Case (after insert) {
//Create list and map for cases
List<case> casesToUpdate = new List<case>();
Map<Id, case> caseMap = new Map<Id, case>();
// Get the default business hours
BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];
// Create Datetime on for now in the local timezone.
Datetime targetTime =System.now();
// Find whether the time now is within the default business hours
Boolean isWithin;
if ( Test.isRunningTest() ){
Boolean isWithin = True;
}
else{
Boolean isWithin = BusinessHours.isWithin(bh.id, targetTime);
}
// Update cases being inserted if during business hours
If (isWithin == True){
// Add cases to map if not null
For(case newcase : trigger.new) {
if(newcase.id != null){
caseMap.put(newcase.Id, newcase);
}
}
// Check that cases are in the map before SOQL query and update
If(caseMap.size() > 0){
// Query cases
casesToUpdate = [SELECT Id, Created_During_Business_Hours__c FROM case WHERE Id IN: caseMap.keySet()];
// Assign new value for checkbox field
for (case c: casesToUpdate){
c.Created_During_Business_Hours__c = TRUE;
}
// if the list of cases isnt empty, update them
if (casesToUpdate.size() > 0)
{
update casesToUpdate;
}
}
}
}
and here is my test class:
@isTest
private class BusinessHoursTest {
@isTest static void createCaseNotInBusinessHours() {
case c = new case();
c.subject = 'Test Subject';
insert c;
}
}