DateTime.AddDays传递什么值来生成异常

时间:2014-11-07 09:37:16

标签: c# unit-testing

我有一个小实用程序类,它使用输入数据生成哈希代码。什么课和&它的算法对于这个问题并不重要,但它看起来如下:

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;
    }
}

我正在为这个课程编写单元测试用例,并意识到AddDays()可以在行下面ArgumentOutOfRangeException

var expiryDate = todayDate.AddDays(expireInDays);

所以我应该写一个测试,然后写下测试用例:

    [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");
        }
    }

问题是,我不知道要传递什么导致AddDays()方法抛出异常?我试过传递随机日期,例如2015年1月30日至1日,2015年1月30日等,

我查看了AddDays()方法实现,但无法理解。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

如果您传入int.MaxValue,则最终的值应该超出DateTime的可表示范围,无论原始DateTime是什么。

示例代码,在csharppad.com上测试:

DateTime.MinValue.AddDays(int.MaxValue);

Assert.Fail块中使用finally是错误的,但始终会被调用。目前还不清楚你的测试框架是什么,但我希望有类似的东西:

Assert.Throws<ArgumentOutOfRangeException>(() => /* code here */);

答案 1 :(得分:0)

在AddDays方法中使用double.MaxValue作为参数。

DateTime time = DateTime.Now;
time.AddDays(double.MaxValue);

超出DateTime类的功能时会触发ArgumentOutOfRangeException。

答案 2 :(得分:0)

另一种方法可以是:

DateTime.MaxValue.AddDays(1);

DateTime.MinValue.AddDays(DateTime.MaxValue.Day +1);

这些代码应抛出ArgumentOutOfRangeException