I’m new to NUnit and looking for an explination as to why this test fails?
I get the following exception when running the test.
NUnit.Framework.AssertionException: Expected: equivalent to < <….ExampleClass>, <….ExampleClass> >
But 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);
}
}
In order to determine if 2 collections are equal NUnit must eventually compare the values within the collection. In this case the values are of type
ExampleClasswhich is aclass. It does not implement any equality testing (such as overriding Equals and GetHashCode) so NUnit will eventually do a reference comparison. This will fail as each collection contains different instances ofExampleeven though the fields have the same values.You could fix this by adding the following to the
ExampleClassNote: I chose the value 1 for
GetHashCodebecause this is a mutable type and the only truly safe return value for GetHashCode on a mutable type is a constant. If you intend to use this as a key in aDictionary<TKey,TValue>though you will want to revisit this.