Always Obtaining a Future Date in C#

I was working today on building a C# REST client for a historic currency conversion web service and needed to write the unit tests.

A historic currency conversion web service it is a web service that allows the retrieval of the exchange rate of 2 currencies from a specified past date. In order to prevent the user from sending a bad data to the service, I employed some simple measures to verify the user input.

In order to simulate error cases in the unit tests I needed to find a method to create a date that will always be in the future. Below you can see my solution:
//The RIGHT way
[Test]
public void GetConversionRate_DateFutureParameter_ThrowsException()
{
//This will always return a date that will be in the future
DateTime future = DateTime.Now.AddYears(1);
Assert.Throws( typeof(CurrencyConversionException),
() => GrandTrunkCurrencyConversionService.Instance
.GetConversionRate(TEST_CURRENCY_NAME_US_DOLLAR,
TEST_CURRENCY_NAME_AU_DOLLAR,
future) );
}
//The NOT SO RIGHT way
[Test]
public void GetConversionRate_DateFutureParameter_ThrowsException()
{
//Perhaps no one will run this unit test in 10 years. But what if
//someone will?
DateTime notReallyFuture = new DateTime(2023,1,1);
Assert.Throws( typeof(CurrencyConversionException),
() => GrandTrunkCurrencyConversionService.Instance
.GetConversionRate(TEST_CURRENCY_NAME_US_DOLLAR,
TEST_CURRENCY_NAME_AU_DOLLAR,
notReallyFuture) );
}
The main idea is that you will never know for how much time your software will be used, so it's better to play it safe :-).

Q: Since I was talking about past and future, what is the oldest library you wrote and still use today?

No comments :

Post a Comment