Created
April 19, 2019 13:23
-
-
Save b-wilder/ee02adc124a029bc5ca3d3ddbea3b503 to your computer and use it in GitHub Desktop.
Simulating date/time in apex for accurate, time-based testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public with sharing class ProductionCode.cls { | |
... | |
private static void scheduleBatchExecution(){ | |
... | |
//Use in place of DateTime.now() | |
DateTime nowDT = Utilities.getCurrentDateTime(); | |
... | |
} | |
... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IsTest private class TestCode { | |
... | |
private static testMethod void simulateCurrentDateTime(){ | |
... | |
//Set the current date time to test a maintnenance window or other time-specific scheduling logic | |
Utilities.testDateTime = DateTime.newInstance(Date.Today(), Time.newInstance(9, 0, 0, 0)); | |
... | |
} | |
... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public with sharing class Utilities { | |
... | |
public static DateTime testDateTime; | |
... | |
//Used to enable testing of logic that is dependent on the current dateTime; | |
//This will be called in place of DateTime.now() by functional code | |
public static DateTime getCurrentDateTime(){ | |
if(Test.isRunningTest() && testDateTime != NULL){ | |
return testDateTime; | |
} else { | |
return DateTime.now(); | |
} | |
} | |
//Used to enable testing of logic that is dependent on the current dateTime; | |
//This will be called in place of Date.today() by functional code | |
public static Date getCurrentDate(){ | |
if(Test.isRunningTest() && testDateTime != NULL){ | |
return testDateTime.date(); | |
} else { | |
return Date.today(); | |
} | |
} | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment