我有一个名为的对象Content
,它继承自ContentBase
.
ContentBase
是一个具有很少属性的基本类。
Content
完全是空的。它只是从ContentBase
.
public class ContentBase
{
public virtual int Id { get; set; }
public virtual string Application { get; set; }
public virtual string Property1 { get; set; }
public virtual string Property2 { get; set; }
}
public class Content : ContentBase
{
}
使用 Moq 我有这个测试:
[Test]
public void AreEqual_Test()
{
var c1 = new Content() { CultureCode = "Code", ResourceKey = "key", ResourceType = "type", ResourceValue = "value" };
var c2 = new Content() { CultureCode = "Code", ResourceKey = "key", ResourceType = "type", ResourceValue = "value" };
Assert.AreEqual(c1, c2);
}
失败并显示此消息:
Expected: <WebPortal.DomainModels.PresentationModel.Content>
But was: <WebPortal.DomainModels.PresentationModel.Content>
at
NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression, String message, Object[] args)
at WebPortal.DomainModels.Tests.PresentationModel.ContentTests.AreEqual_Test() in ContentTests.cs: line 16
当 Content 没有从 ContentBase 继承时,这不会发生,但我仍然觉得错误消息很荒谬。
Content 类包含这个 Equals:
public override bool Equals(object obj)
{
var content = (Content)obj;
return this.ResourceKey == content.ResourceKey && this.ResourceType == content.ResourceType && this.CultureCode == content.CultureCode;
}
public override int GetHashCode()
{
return this.Id.GetHashCode() + this.Application.GetHashCode();
}
失败的 Assert 不会触发 Equals 方法
Assert.AreEqual(c1, c2);
但是下面的 Assert 确实触发了 Equals 并且测试通过了:
Assert.IsTrue(c1.Equals(c2));
有没有人见过这个?