Assert.AreEqual失败。预期:<xmlresult>。实际:<xmlresult> </xmlresult> </xmlresult>

时间:2012-06-24 23:35:01

标签: c# asp.net-mvc asp.net-mvc-3 unit-testing

我是单元测试的新手,所以我可能做错了。

我有一些XmlResult类:

public class XmlResult : ActionResult
    {
        public XmlDocument Document { private get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            //Do something
        }
    }

我也有控制器扩展方法:

public static class ControllerExtensions
    {
        public static XmlResult Xml(this Controller controller, XmlDocument document)
        {
            return new XmlResult { Document = document };
        }
    }

测试方法:

[TestClass]
    public class ControllerExtensionsTests
    {
        #region Xml
        [TestMethod]
        public void XmlExtensionShouldReturnCorrectValue()
        {
            // Arrange
            var mockRepository = new Mock<T>();
            var productsController = new ProductController(mockProductRepository.Object);

            var someXmlDocument = new XmlDocument();

            // Act
            var actual = productsController.Xml(someXmlDocument);
            var expected = new XmlResult { Document = someXmlDocument };

            // Assert
            Assert.AreEqual(expected, actual);               
        }
        #endregion
    }

当我致电Assert.AreEqual(expected, actual);时,我的测试失败并显示消息"Assert.AreEqual failed. Expected:<XmlResult>. Actual:<XmlResult>."。我做错了什么???

1 个答案:

答案 0 :(得分:2)

我会在你的xml结果类中添加一个override equals方法,并为equals比较做你自己的实现。

下面的东西......

public class XmlResult : ActionResult
{
    public XmlDocument Document { private get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        //Do something
    }

    public bool Equals(XmlResult other)
    {
        if(ReferenceEquals(null, other))
        {
            return false;
        }
        if(ReferenceEquals(this, other))
        {
            return true;
        }
        return Equals(other.Document, Document);
    }

    public override int GetHashCode()
    {
        return (Document != null ? Document.GetHashCode() : 0);
    }
}