NUnit, CollectionAssert.AreEquivalent (..., ...), C # Question

I am new to NUnit and looking for an explanation as to why this test fails?

When I run the test, I get the following exception.

NUnit.Framework.AssertionException: Expected: Equivalent to <<.... ExampleClass>, <.... ExampleClass β†’ But there was: <.... ExampleClass>, <.... ExampleClass β†’

using NUnit.Framework; using System.Collections.ObjectModel; public class ExampleClass { public ExampleClass() { Price = 0m; } public string Description { get; set; } public string SKU { get; set; } public decimal Price { get; set; } public int Qty { get; set; } } [TestFixture] public class ExampleClassTests { [Test] public void ExampleTest() { var collection1 = new Collection<ExampleClass> { new ExampleClass {Qty = 1, SKU = "971114FT031M"}, new ExampleClass {Qty = 1, SKU = "971114FT249LV"} }; var collection2 = new Collection<ExampleClass> { new ExampleClass {Qty = 1, SKU = "971114FT031M"}, new ExampleClass {Qty = 1, SKU = "971114FT249LV"} }; CollectionAssert.AreEquivalent(collection1, collection2); } } 
+6
c # nunit
source share
2 answers

To determine if 2 collections are equal, NUnit must ultimately compare the values ​​inside the collection. In this case, the values ​​are of type ExampleClass , which is equal to class . It does not implement any equality testing (for example, overrides Equals and GetHashCode), so NUnit will eventually make a comparative comparison. This will fail because each collection contains different instances of Example , although the fields have the same values.

You can fix this by adding the following to ExampleClass

 public override bool Equals(object o) { var other = o as ExampleClass; if ( other == null ) { return false; } return this.Description == other.Description && this.SKU == other.SKU && this.Price == other.Price && this.Qty == other.Qty; } public override int GetHashCode() { return 1; } 

Note. I chose a value of 1 for GetHashCode because it is a mutable type, and the only really safe return value for GetHashCode on a mutable type is constant. If you intend to use this as a key in Dictionary<TKey,TValue> , although you will want to return to it.

+10
source share

You need to implement Equals and GetHashCode on ExampleClass . Without this, NUnit performs a check for equality ("are they the same object?"), And not equality of values ​​("do these objects look alike?").

+6
source share

All Articles