比较两个列表时单元测试失败

时间:2013-07-08 14:31:26

标签: c# .net unit-testing ilist

我正在运行一些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). "}

失败

通过检查对象看起来是一样的

原创

enter image description here

反序列化对象

enter image description here

问题

比较IList对象进行单元测试的最佳方法是什么?为什么我的测试失败了?

1 个答案:

答案 0 :(得分:4)

您需要为Equals课程定义GetHashCodeBusinessModel。默认的Equals实现是引用相等,并且对象引用对于两个列表中的项目将是不同的。

或者,您可以创建一个定义相等/哈希码的IEqualityComparer<BusinessModel>并将其传递给SequenceEquals