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 am running MSTest with VS 2008.

+4
source share
5 answers

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

If you have not overloaded Equals and GetHashCode in your class, the equality check of the backup object will fail because the sequences contain two different objects.

+6
source

Presumably because ReportReceipt does not override Equals - therefore it only compares links, and they are unequal.

Replace Equals and GetHashCode respectively, and it should work fine.

+3
source

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

Add 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); } 
0
source

You are comparing two different instances of reference objects β€” this way they will not be equal unless you implement Equals in a type to check property values ​​instead of links.

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

0
source

If you want to use your own resolver to determine equality, you can use the overload of this method described in MSDN

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

0
source

Source: https://habr.com/ru/post/1312732/


All Articles