Unit Testing with DateTime.Now

I recently had to write some unit tests for a method which had various outcomes depending on the current Date/Time, this created a problem as the method used DateTime.Now and there is no way to moq┬áit. I tried a few different ways of doing this and did a bit of Googling and came up with the following solution. I can’t take credit for this as it came from this stackoverflow post.

The way this works is that you use SystemTime within your methods instead of DateTime and then change the value depending on the test using SetDateTime.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.