Daniel Hoelbling-Inzko talks about programming
There is one excellent point Roy Osherove made while reviewing the tests in NerdDinner.com I wanted to share with you.
Don’t write tests that change over time!
Often I have initialized objects for tests like this:
[Fact] public void Test() { DateTime date = DateTime.Now; ... }
Until recently I thought that’s cool, after all the tests passed every time I ran them.
But what if the passing tests are just a coincidence?
What if I am testing a financial application that will only accept orders between 8am and 6pm on weekdays, and the order-date gets initialized to DateTime.Now in my test?
Given the normal work days in most countries that code would run for most developers just fine, but when some notorious late-worker like me comes in the tests start failing for no apparent reason.
Time or place of execution, should not have an impact on a test at all. Given the same code and the same test, the result should always be the same.
So, whenever you initialize a value to something from your current execution context (time being the prime example here), you create a possibility that this test will break in some unexpected ways over time.
So if you really want to fill some DateTime with a value for testing use a constant (like DateTime.MinValue/MaxValue). So whenever you re-run this test all inputs are the same as they have been when you wrote the test.