How do you make DateTime testable in .NET? Once you use DateTime.UtcNow
in the body of a method and you did not pass it as a parameter you no longer have control over DateTime.
In order to gain control you should wrap DateTime.UtcNow inside an implementation of an interface.
public interface IUtcDateTime
{
DateTime UtcNow { get; }
}
public class UtcDateTime : IUtcDateTime
{
public DateTime UtcNow { get; } => DateTime.UtcNow;
}
Now you can let IUtcDateTime be injected by your Depency Injection framework of your choice and write unit tests. An additional benefit is that you are sure that the right usage of DateTime is used. In larger projects it becomes harder to spot mistakes like DateTime.Now
vs DateTime.UtcNow
.