Hide DateTime.Now behind ITimeProvider?
To make code unit testable there is often a need to break dependencies between classes. This is normally done by hiding concrete implementations behind interfaces and injecting those interfaces into the class that you want to test.
What if your code is dependent on the static DateTime.Now? Should you hide that behind an interface called ITimeProvider and suddenly have to pass that interface around?
In his book "The Art of Unit Testing", Roy Osherove suggests that you don't and that you use a solution like this class instead:
public class SystemTime
{
private static DateTime? _date;
public static void Set(DateTime custom)
=> _date = custom;
public static void Reset()
=> _date = null;
public static DateTime Now
=> _date ?? DateTime.Now;
}
If you create such a class, then you can replace all the calls to DateTime.Now in your code to SystemTime.Now.
And in your unit tests you can use SystemTime.Set() to set what date should be returned from SystemTime.Now. After each test run, make sure to call SystemTime.Reset(). That call is preferably put in a teardown method, like [TestCleanup] if you're using MSTest or [TearDown] in NUnit.
Inga kommentarer:
Skicka en kommentar