0

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

我有一些 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>."。我究竟做错了什么???

4

1 回答 1

2

我会在你的 xml 结果类上添加一个覆盖 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);
    }
}
于 2012-06-25T01:12:46.897 回答