不理解Assert.Areequal背后的编码

时间:2012-11-08 20:56:08

标签: c#

任何人都可以帮我吗?

 [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()
    {
        /* HINT You need to use a try ... catch block in the MakeDate()
         * method to trap the exception thrown by the DateTime constructor.
         * See http://msdn.microsoft.com/en-us/library/xcfzdy4x(v=vs.110)/ 
         * for information on the exceptions thrown by the DateTime 
         * constructor.  
         * See http://msdn.microsoft.com/en-us/library/ms173160(v=vs.110).aspx 
         * for information on exception handling in C#.  
         * */
        //Arrange
        var controller = new DateController();//error
        var expected = new DateTime();//error

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

不断收到错误说明错误预期的类,委托,枚举,接口或结构 //在'void,datacontroller和datetime

下获取错误

2 个答案:

答案 0 :(得分:1)

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

该行代码 Asserts 它的两个参数 Are Equal 。这是一个通用方法,因此<DatTime>位告诉方法两个参数的类型是什么。类似的东西:

bool SomeGenericCompareMethod<T>( T arg1, T arg2 )
{
    // use reference equality by default, 
    // implementation may override .Equals()
    return arg1.Equals( arg2 );
}

编辑:

根据评论中完全没有格式化和乱码的代码,这究竟是什么?

Arrange var controller = new DateController();//Getting Error

这没有任何意义。您似乎有两个类型声明符Arrangevar。选一个。我会这样做,因为ArrangeDateController派生自的基类/接口并不清楚:

var controller = new DateController();//Getting Error

答案 1 :(得分:0)

断言可以在应用程序中用作运行时cheks(即您提到的方法比较两个参数并使用相等运算符验证它们是否相等)。

如果断言评估为true,它只是让代码继续,但如果它评估为false,则抛出AssertFailedException

有关msdn的一些信息,请看一下:http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert%28v=vs.80%29.aspx