Randomness in Unit Tests

Poker set 2

Most of us programmers are writing unit tests for at least some of their code. This is very fine.

And, as I’ve seen in one of my latest projects, many of us have had the idea to use randomness in these unit tests. On the one hand, this good: With randomness, more different inputs are tested.
On the other hand, this is bad: Because if the seed of the random number generator is not known, we cannot reproduce a failing test.
So it could be the case that we have a nightly build with failing tests, but no way to reproduce (and hence debug) them because of the random input.

The solution: Use a seed that is based on the day, but not on on hours, minutes, seconds or ticks. This way we have both advantages: testing regularly with different input, but also easy reproducibility if one knows the day on which the test was run.
In C#, like this:

static DateTime now = DateTime.Now;
static int seed = (now.Year << 16) + (now.Month << 8 ) + now.Day;
static Random randomGenerator = new Random(seed);