我正在尝试创建一个单元测试来比较两个字符串数组列表。
我尝试创建两个完全相同的 List<string[]>
对象,但是当我使用 CollectionAssert.AreEqual(expected, actual);
,测试失败:
[TestMethod]
public void TestList()
{
List<string[]> expected = new List<string[]> {
new string[] { "John", "Smith", "200" },
new string[] { "John", "Doe", "-100" }
};
List<string[]> actual = new List<string[]> {
new string[] { "John", "Smith", "200" },
new string[] { "John", "Doe", "-100" }
};
CollectionAssert.AreEqual(expected, actual);
}
我也试过 Assert.IsTrue(expected.SequenceEqual(actual));
,但这也失败了。
如果我比较两个字符串列表或两个字符串数组,这两种方法都有效,但在比较两个字符串数组列表时它们不起作用。
我假设这些方法失败了,因为它们正在比较两个对象引用列表而不是数组字符串值。
我如何比较这两个 List<string[]>
对象并判断它们是否真的相同?
最佳答案
失败是因为列表中的项目是对象 (string[]
) 并且因为您没有指定 CollectionAssert.AreEqual
应该如何比较两者中的元素sequences 它正在回退到默认行为,即比较引用。例如,如果您将列表更改为以下内容,您会发现测试通过了,因为现在两个列表都引用了相同的数组:
var first = new string[] { "John", "Smith", "200" };
var second = new string[] { "John", "Smith", "200" };
List<string[]> expected = new List<string[]> { first, second};
List<string[]> actual = new List<string[]> { first, second};
为了避免引用比较,您需要告诉 CollectionAssert.AreEqual
如何比较元素,您可以通过在调用它时传入 IComparer
来实现:
CollectionAssert.AreEqual(expected, actual, StructuralComparisons.StructuralComparer);
关于c# - 在 C# 单元测试中比较两个 List<string[]> 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269493/