Member-only story
5 Ways to Mock DateTime.Now for Unit Testing in C#
With pros and cons of each.
Abstracting the application logic from DateTime.Now
property is a common task for developers to enable unit testing.
When DateTime
is hard-coded into logic, unit tests will not be reliable.
In the following example, a unit test can only pass if it is executed on a very fast machine:
DateTime.Now
instance used in application logic will often have a different number of milliseconds / ticks than DateTime.Now
used in test case assertion.
There are at least 5 ways to solve the DateTime.Now
problem in unit tests and make them run predictably.
1. IDateTimeProvider Interface
One of the most common approaches is to introduce an interface that the application logic will use instead of the direct use of DateTime.Now
property.
Pros:
- The
IDateTimeProvider
dependency is an explicit one. To understand whether a particular class works with theIDateTimeProvider
, developers just need to look at the class constructor. There is no need to analyze the rest of the class logic. - It is more natural to have a method that returns the current
DateTime
than a property. Typically, when C# developers call the same property multiple times, they expect to get the same value.
Cons:
- Many class constructors across all codebase will have an additional
IDateTimeProvider
parameter in the list that pollutes the code. - It is necessary to register the interface and implementation in the DI- container.
- Nothing prevents developers from using the
DateTime
type…