Dave Hogan
Dave Hogan

Reputation: 3221

How to write Unit Test for time sensitive constant

This might be an obvious answer to this but I can't figure out how best to create a unit test for the following:

Assert.AreEqual(27, AgeCalculator.GetAge(new DateTime(1983, 10, 6))); // this test will fail tomorrow
Assert.AreEqual(26, AgeCalculator.GetAge(new DateTime(1984, 11, 14)));
Assert.AreEqual(9, AgeCalculator.GetAge(new DateTime(2002, 05, 7)));
Assert.AreEqual(7, AgeCalculator.GetAge(new DateTime(2003, 11, 03)));
Assert.AreEqual(4, AgeCalculator.GetAge(new DateTime(2007, 05, 10)));

I've created a GetAge() method that I want a test to ensure any future changes to that method are OK.

Upvotes: 0

Views: 922

Answers (2)

skaz
skaz

Reputation: 22580

I would mock the datetime object inside of your AgeCalculator so that it always uses the same testing date.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

Take a look at the following blog post which is part of a nice series of posts for testing against non-determinism.

Upvotes: 2

Related Questions