January 8, 2010 Leave a comment
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:
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.