5 Ways to Mock DateTime.Now for Unit Testing in C#

With pros and cons of each.

Sasha Marfut
Level Up Coding
Published in
3 min readJul 20, 2021

--

Photo by Luke Chesser on Unsplash

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:

--

--