无法比较 UnitTests 中的列表 [英] Cannot compare lists in UnitTests
问题描述
我需要在我的单元测试中比较如下列表:
I need to compare lists like the following in my unit tests:
var x = new List<object>() { new List<int>() };
var y = new List<object>() { new List<int>() };
CollectionAssert.AreEqual(x, y, "Expected response not the same as actual response.");
但我总是遇到下面的异常,我该如何克服这个问题?
But I am always getting the exception below, how do I go about overcoming this?
[Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException] ={"CollectionAssert.AreEqual 失败.预期响应与实际响应.(索引 0 处的元素不匹配.)"}
[Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException] = {"CollectionAssert.AreEqual failed. Expected response not the same as actual response.(Element at index 0 do not match.)"}
推荐答案
作为替代方案,您可以考虑使用 FluentAssertions
单元测试框架,与微软单元测试兼容.
As an alternative, you could consider using the FluentAssertions
Unit Test framework, which is compatible with Microsoft Unit Test.
那么你的代码会变成:
var x = new List<object>() { new List<int>() };
var y = new List<object>() { new List<int>() };
x.ShouldBeEquivalentTo(y, "Expected response not the same as actual response.");
它也适用于这种事情:
var ints1 = new List<int>();
var ints2 = new List<int>();
ints1.Add(1);
ints2.Add(1);
var x = new List<object>() { ints1 };
var y = new List<object>() { ints2 };
x.ShouldBeEquivalentTo(y, "Expected response not the same as actual response.");
如果您将 ints2.Add(1);
更改为 ints2.Add(2);
,则单元测试将正确失败.
If you changed ints2.Add(1);
to ints2.Add(2);
, the unit test would then correctly fail.
请注意,ShouldBeEquivalentTo()
递归地降低被比较的对象,并处理集合,因此即使是列表列表也可以使用它 - 例如:
Note that ShouldBeEquivalentTo()
recursively descends the objects being compared, and handles collections, so even lists of lists will work with it - for example:
var ints1 = new List<int>();
var ints2 = new List<int>();
ints1.Add(1);
ints2.Add(1); // Change this to .Add(2) and the unit test fails.
var objList1 = new List<object> { ints1 };
var objList2 = new List<object> { ints2 };
var x = new List<object> { objList1 };
var y = new List<object> { objList2 };
x.ShouldBeEquivalentTo(y, "Expected response not the same as actual response.");
这篇关于无法比较 UnitTests 中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!