Can you override Date.Now or Date.Today for debugging purposes in an ASP.NET web application?

We have a very massive system in which reports are run from dates from specific days to today using various definitions of "GenerateSalesReport (DateStart, Date.Now)".

For debugging purposes, I want to simulate reports that occurred in the past, so I need to change the "Date.Now" object to a specific date from the past in my development environment. Is it possible to override date.Now ?

+4
source share
3 answers

This is one of the disadvantages of DateTime.Now and related functions.

You must pass DateTime any function that relies on it. Any place where you use DateTime.Now or DateTime.Today (and such) is the place where you should pass in a date.

This allows you to test different DateTime values, make your code more testable and remove the time dependency.

+6
source

A good solution is to abstract the external dependencies in order to be able to drown them out during the test. To virtualize time, I often use something like this:

 public interface ITimeService { DateTime Now { get; } void Sleep(TimeSpan timeSpan); } 

In your case, you do not need the Sleep part, since you will depend only on the current time, and, of course, you need to change your code to use the ITimeService supplied from the outside when the current time is required.

Usually you should use this implementation:

 public class TimeService : ITimeService { public DateTime Now { get { return DateTime.Now; } public void Sleep(TimeSpan timeSpan) { Thread.Sleep(timeSpan); } } 

For testing purposes, you can use this stub:

 public class TimeServiceStub : ITimeService { public TimeServiceStub(DateTime startTime) { Now = startTime; } public DateTime Now { get; private set; } public void Sleep(TimeSpan timeSpan) { Now += timeSpan; } } 
+3
source

Even if it were possible, you probably would be better off changing the system time. Otherwise, you created a completely new test case (where your system runs at different times than any other process in the system). Who knows what problems you might face.

-1
source

All Articles