Skip to content

Instantly share code, notes, and snippets.

@b-wilder
Created April 19, 2019 13:23
Show Gist options
  • Save b-wilder/ee02adc124a029bc5ca3d3ddbea3b503 to your computer and use it in GitHub Desktop.
Save b-wilder/ee02adc124a029bc5ca3d3ddbea3b503 to your computer and use it in GitHub Desktop.
Simulating date/time in apex for accurate, time-based testing
public with sharing class ProductionCode.cls {
...
private static void scheduleBatchExecution(){
...
//Use in place of DateTime.now()
DateTime nowDT = Utilities.getCurrentDateTime();
...
}
...
}
@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));
...
}
...
}
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