简体   繁体   中英

Why does this Assert fail?

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

IEnumerable<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM