Unit testing methods with date/time in .net

One of the very important rules of unit testing is to make sure that the result of the test is predictable and repeatable. This is fairly straight forward to achieve in most cases by using constants instead of random values for example but how do we deal with methods using the current date and/or time?

If we just use the DateTime.Now property, the value will change for each test run which will cause us to have unpredictable and sometimes unrepeatable results.

The solution to this problem is pretty simple, create a wrapper class for the DateTime methods that we may need so we can mock the call to methods returning time dependent values.

A very basic wrapper class could look like this:

   1: using System;


   3: public interface IDateTime

   4: {

   5:     #region Methods


   7:     DateTime Now();


   9:     #endregion Methods

  10: }


  12: public class DateTimeWrapper : IDateTime

  13: {

  14:     #region Public Methods


  16:     public DateTime Now()

  17:     {

  18:         return DateTime.Now;

  19:     }


  21:     #endregion Public Methods

  22: }


We can now use the DateTimeWrapper implementation of IDateTime in our code and the IDateTime interface can easily be mocked to return a constant value for the Now() method call.