我正在运行一些TestMethods来测试JSON序列化程序的实现,并在序列化\反序列化之前和之后比较两个IList对象,但比较失败。
模型
public class BusinessModel
{
public int ID { get; set; }
public string Name { get; set; }
}
测试
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));
}
结果
我在this帖子中尝试了一些详细的测试方法,但都失败了。
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);
}
传递集合计数项但在第一次对象比较时失败。
Assert.IsTrue(model.SequenceEqual(deserialisedModel));
以Assert.IsTrue failed
CollectionAssert.AreEqual(model.ToArray(),deserialisedModel.ToArray())
以Collection.AreEqual failed (Element at index 0 do not match)
CollectionAssert.AreEquivalent(model.ToArray(),deserialisedModel.ToArray())
以{"CollectionAssert.AreEquivalent failed. The expected collection contains 1 occurrence(s) of <Helper.Tests.Serialisation.BusinessModel>. The actual collection contains 0 occurrence(s). "}
通过检查对象看起来是一样的
原创
反序列化对象
问题
比较IList对象进行单元测试的最佳方法是什么?为什么我的测试失败了?
答案 0 :(得分:4)
您需要为Equals
课程定义GetHashCode
和BusinessModel
。默认的Equals
实现是引用相等,并且对象引用对于两个列表中的项目将是不同的。
或者,您可以创建一个定义相等/哈希码的IEqualityComparer<BusinessModel>
并将其传递给SequenceEquals
。