Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

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:

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 the IDateTimeProvider, 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…

--

--

Written by Sasha Marfut

1 million+ views on Medium | .NET, Design Patterns, Architecture, API

Responses (4)

Write a response