I have a small utility class that generate a hash code with input data. What class does & its algorithm is not significant to the question but it looks like below:
public static class HashCodeHelper
{
/// <summary>
/// Return a hash code to be added to the link in download data.
/// </summary>
/// <param name="baseDateTime">Today's date</param>
/// <param name="rrid">Profile ID</param>
/// <param name="downloadCode">Download code to be used for hash code generation.</param>
/// <returns>Final result is a string in this format "20140715385"</returns>
public static string GenerateHashCodeForExportLink(DateTime baseDateTime, int rrid, string downloadCode)
{
var todayDate = baseDateTime;
int expireInDays;
if (!int.TryParse(ConfigurationManager.AppSettings["ExportLinkExpireInDays"], out expireInDays))
expireInDays = 30; // If not specified in web.config file then use default value
var expiryDate = todayDate.AddDays(expireInDays);
var currentDay = todayDate.Day;
var expiryMonth = expiryDate.Month;
char nthChar = Convert.ToChar(downloadCode.Substring(expiryMonth - 1, 1));
var asciiValue = (int)nthChar;
var mod = (rrid % currentDay);
var computedHash = (asciiValue * expiryMonth) + currentDay + mod;
var fullHashCode = todayDate.ToString("yyyyMMdd") + computedHash;
return fullHashCode;
}
}
I was writing unit test cases for this class and realized that AddDays()
can throw an ArgumentOutOfRangeException
, below line:
var expiryDate = todayDate.AddDays(expireInDays);
So I should write a test and i did write below test case:
[TestMethod]
public void GenerateHashCodeForExportLink_IncorrectDate_Throw()
{
try
{
HashCodeHelper.GenerateHashCodeForExportLink(new DateTime(2015, 1, 31), 501073, "001-345-673042");
Assert.Fail("Exception is not thrown");
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception)
{
Assert.Fail("Incorrect exception thrown");
}
}
The problem is, i do not know what to pass to cause AddDays()
method to throw exception? I tried passing random dates e.g. 1-1-1800, 30-Jan-2015, etc.
I looked at AddDays()
method implementation but could not make out. Any idea?
If you pass in int.MaxValue
, that should end up with a value which is outside the representable range for DateTime
, whatever the original DateTime
is.
Sample code, tested on csharppad.com:
DateTime.MinValue.AddDays(int.MaxValue);
Using Assert.Fail
in a finally
block is a mistake though... that will always be called. It's not clear what your test framework is, but I'd expect something like:
Assert.Throws<ArgumentOutOfRangeException>(() => /* code here */);
See more on this question at Stackoverflow