Tests should last forever
March 25th, 2009 . by Daniel HölblingThere 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.



Hello Daniel,
you are absolutly right about this point. But how can you manage to test a function which only works for the current day or the current week? In this case you also must have test which changes every day. But you have to think about a lot of things. Maybe the function does not work on sunday or only between 8 and 16 etc.
best regards
Harald
The whole point of the posting was that if you initialize a variable in your test to DateTime.Now, your test changes dynamically at runtime. So if your code under test makes some checks to that variable, you'll end up with a test that isn't running 100% of the time.
If you initialize the variable to some fixed date where you know it should pass (like 1.1.2009 14:00), you can rerun the test under any condition, it will still pass as long as the code works as expected.
[...] Oh, and btw: The example I did above was chosen deliberately to be something as simple as a abstraction of DateTime.Now. As said before, never depend on moving parts in your tests. [...]
Mark S. is definitely on the right track. If you want to get a professional looking email address, Id recommend buying your name domain name, like or
Jordan Pro Classic
If its common it might be difficult to get, however, be creative and you can usually find something.
Mark S. is definitely on the right track. If you want to get a professional looking email address, Id recommend buying your name domain name, like or
air jordan 16.5
If its common it might be difficult to get, however, be creative and you can usually find something.