You need to sign in to do that
Don't have an account?
Unit Tests for Date/Time Dependent Apex
I am sort of struggling to figure out what best practices are for testing time and date dependent apex.
Example:
I have an apex class that generates something like customer statements. The class sets a date variable using System.today() and figures out the month. Based on the month, it responds differently. In December, for example, it calculates a year end summary but does not calculate this any other month of the year.
When writing unit tests, I need to be able to test every month to make sure it's repsonding correctly.
How have others addressed this? I could have a testMode Boolean variable that I could set to tell the class to use the System date (testMode = false) or a supplied date in another variable (testMode = true).
Is this considered best practices?
You wouldn't need to have a boolean, as Apex now provides the Test.isRunningTest() method.
This is exactly how I test this sort of code in Apex and always did in Java before I switched to Salesforce. Essentially its allowing dependency injection when running in test mode, which IMHO is the cleanest way to do it.