-1

I am new on MVC3 and not familiar with the unit testing part. I have been trying to construct Datetime with exception handling from accepting 3 integer value but the it fails the unit testing. Im not sure i am doing it correctly or not.

This is the controller part:

public DateTime MakeDate(string dateString)
    {
     DateTime myDate;
        if (DateTime.TryParseExact(dateString, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out myDate))
        {
            return myDate;
        }
        return new DateTime();
    }

And this is the unit Testing:

[TestMethod]
public void MakeDateConstructsADateTimeFromYearMonthAndDay()
{
    //Arrange
    var controller = new DateController();
    var expected = new DateTime(2014, 6, 30);

    //Act
    var result = controller.MakeDate(2014, 6, 30);

    //Assert
    Assert.AreEqual<DateTime>(expected, result);
}

[TestMethod]
public void MakeDateReturnsDefaultDateTimeIfInputDataInvalid()
{
    var controller = new DateController();
    var expected = new DateTime();

    //Act
    //June has only 30 days so this will cause an exception
    var result = controller.MakeDate(2014, 6, 31);

    //Assert
    Assert.AreEqual<DateTime>(expected, result);
 }

Thanks in advance

4

2 回答 2

0

尝试将您的MakeDate功能更改为以下内容:

DateTime myDate;
if (DateTime.TryParseExact(dateString, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out myDate))
{
    return myDate;
}
return new DateTime();

此外,您的MakeDate函数不使用dr参数,并且您指定格式的日期yyyy-MM-dd并使用ParseExact不同的格式 ( yyyyMMdd)。

于 2013-01-17T14:36:09.953 回答
0
string date = "2014-06-30";
DateTime datetime = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);

您的date字符串不是您在ParseExact.

yyyyMMdd在应该使用的时候使用yyyy-MM-dd

代码失败,因为字符串与格式不匹配。

于 2013-01-17T14:17:25.707 回答