I am running some TestMethods thats tests the implementation of a JSON serialiser and when comparing two IList objects before and after the serialisation \ de-serialisation but the comparison is failing.
Model
public class BusinessModel
{
public int ID { get; set; }
public string Name { get; set; }
}
Test
IList<BusinessModel> model = new List<BusinessModel>
{
new BusinessModel { ID = 1, Name = "Test1" },
new BusinessModel { ID = 2, Name = "Test2" },
new BusinessModel { ID = 3, Name = "Test3" },
new BusinessModel { ID = 4, Name = "Test4" }
};
[TestMethod]
public async Task TestSerialiseDeserialiseIsEqual()
{
ISerialiser serialiser = new Serialiser();
IList<BusinessModel> deserialisedModel;
string serialised = string.Empty;
serialised = await serialiser.SerialiseAsync<IList<BusinessModel>>(model);
deserialisedModel = await serialiser.DeserialiseAsync<IList<BusinessModel>>(serialised);
Assert.IsTrue(model.SequenceEqual(deserialisedModel));
}
Results
I have tried a number of test methods detail in this post but all are failing.
Assert.AreEqual(t1.Count(), t2.Count());
IEnumerator<Token> e1 = t1.GetEnumerator();
IEnumerator<Token> e2 = t2.GetEnumerator();
while (e1.MoveNext() && e2.MoveNext())
{
Assert.AreEqual(e1.Current, e2.Current);
}
passes the collection count items but fails on the first object comparison.
Assert.IsTrue(model.SequenceEqual(deserialisedModel));
fails with Assert.IsTrue failed
CollectionAssert.AreEqual(model.ToArray(),deserialisedModel.ToArray())
fails with Collection.AreEqual failed (Element at index 0 do not match)
CollectionAssert.AreEquivalent(model.ToArray(),deserialisedModel.ToArray())
fails with {"CollectionAssert.AreEquivalent failed. The expected collection contains 1 occurrence(s) of <Helper.Tests.Serialisation.BusinessModel>. The actual collection contains 0 occurrence(s). "}
From checking the objects they look the same
Original
Deserialised Object
Question
What is the best method in comparing IList objects for Unit Testing? Why are my tests failing?
You need to define Equals
and GetHashCode
for your BusinessModel
class. The default Equals
implementation is reference equality, and your object references will be different for the items in the two lists.
Alternatively you can create an IEqualityComparer<BusinessModel>
which defines equality/hash code and pass that to SequenceEquals
.