c# - 在 C# 单元测试中比较两个 List<string[]> 对象

标签 c# arrays list unit-testing equality

我正在尝试创建一个单元测试来比较两个字符串数组列表。

我尝试创建两个完全相同的 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/

相关文章:

python - 努力使用切片语法来连接列表的一部分的列表元素

c# - 如何在 ASP MVC4 中实现包含多个单词的搜索功能?

c# - 将万无一失的 RequiredIf 与枚举一起使用

c# - 如何在 C# 中将 serilog 记录器添加到 GenericHost 项目

javascript - 创建一个接受字符串并将重复值分组的函数

c - 在函数中修改字符串 (char*) 后,除非在函数内部打印,否则该值不会显示

C# 多线程 : Do I have to use locks when only getting objects from a list/dictionary?

python - 在 Python 模块中初始化静态列表的最佳方法

c# - 如何将其写入 linq to object 查询?

我可以静态分配这个字符串吗?如何?