I really like this suggestion on StackOverflow to use an IClock interface to supply your code with the current date/time so you can supply a different date/time when unit testing (not to mention factoring out all of the DateTime.Now references).
I can use dependency injection to supply an implementation of this interface to my service layer.
However, I have alot of DateTime.Now references in my entities (sample below). What is the preferred way of addressing this?
public class SampleEntity
{
private DateTime someField;
private DateTime someOtherDate;
public SampleEntity()
{
someField = DateTime.Now;
}
public bool SomeProperty
{
get { return someOtherDate < DateTime.Now.Date; }
}
public bool SomeFunction()
{
return SomeOtherDate < DateTime.Now.Date;
}
}
I can pass in parameters to the function and/or constructor, but that still requires me to explicitly set something if I retrieve the entity from an ORM.
If you want to use
IClock, you will have to replace allDateTime.NowwithClock.Nowand have your class take anIClockinstance in the constructor:As far as passing the concrete implementation of an
IClockwhen instantiating the entity most ORM frameworks provide hooks that could be used to provide custom instances of the entities.If your ORM doesn’t provide such hooks you could still use the accepted answer from the linked question which uses a
public static Func<DateTime> Now = () => DateTime.Now;provider.