开发者

Why does this Assert fail?

IEnumerable<ReportReceipt> expected = new List<ReportReceipt>()
{
    new ReportReceipt("fileName1","Hash1","some comments1")
};

IEnumerable&l开发者_如何学编程t;ReportReceipt> actual = new List<ReportReceipt>()
{
    new ReportReceipt("fileName1","Hash1","some comments1")
};

Assert.IsTrue(expected.SequenceEqual(actual));

I'm running MSTest with VS 2008.


SequenceEqual determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

If you haven't overloaded the Equals and GetHashCode in your class, the fallback object equality check will fail, since the sequences contain two different objects.


Presumably because ReportReceipt doesn't override Equals - so it's comparing just the references, and they're unequal.

Override Equals and GetHashCode appropriately and it should work fine.


Have you overloaded the equality operator for ReportReceipt? Is the SequenceEqual method not testing for equality location of ReportReceipt in memory, not the contents of the object? Overriding Equals and GetHashCode should solve your problem.

Add something like the following to ReportReceipt:

public override bool Equals(object obj)
{
            if (obj == null || obj.GetType() != this.GetType)
                return false;
            ReportReceipt other = (ReportReceipt)obj;
            return this.FileName.Equals(other.FileName)
                && this.Hash.Equals(other.Hash);
        }


You are comparing two different instances of reference objects - thus, they won't be equal unless you implement Equals on the type to check property values instead of references.

To make this easier, use CollectionAssert.AreEquivalent() instead.


If you want to use you own comparer to determine equality, you can user the overload of this method described on MSDN

Basically you will pass an IEqualityComparer<TSource> as parameter which will be used to compare the elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜