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;

   2:

   3: public interface IDateTime

   4: {

   5:     #region Methods

   6:

   7:     DateTime Now();

   8:

   9:     #endregion Methods

  10: }

  11:

  12: public class DateTimeWrapper : IDateTime

  13: {

  14:     #region Public Methods

  15:

  16:     public DateTime Now()

  17:     {

  18:         return DateTime.Now;

  19:     }

  20:

  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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: