About Me

Wednesday, December 1, 2010

How to write unit test for DateTime.Now

Yesterday I tried to use test driven development (TDD) to create logic for the application I'm working on.

One of requirements was to make the module to set the date when the object was modified.
The object has a property UpdatedOn and i needed to write a test that checks setting of DateTime.Now value for it.

The problem is, regular solution like the one below, will not work:


Assert.AreEqual(DateTime.Now, someObject.UpdatedOn);

The reason of why that example will always failed, is because the result of execution of DateTime.Now in Assert and DateTime.Now in business logic will be always different.
There will be few miliseconds between them and the test will always failed.

Here is what i used instead:


Assert.That(someObject.UpdatedOn, Is.EqualTo(DateTime.Now).Within(1).Seconds);


No comments:

Post a Comment