FluentAssertions Should.Equal on collections,包含null

ten*_*gma 5 c# fluent-assertions

当我尝试将两个集合与空值进行比较时,FluentAssertions似乎因NullReferece异常而失败

    [Test]
    public void DeepWithNulls()
    {
        var l1 = new List<string> { "aaa", null };
        var l2 = new List<string> { "aaa", null };

        l1.Should().Equal(l2);
    }
Run Code Online (Sandbox Code Playgroud)

比较在没有空值的集合上按预期工作.

Har*_*san 4

发生这种情况是因为在集合比较逻辑的深处 Fluent Assertion 使用以下代码

 for (int index = 0; index < expectedItems.Length; index++)
            {
                verification.ForCondition((index < actualItems.Length) && actualItems[index].Equals(expectedItems[index]))
                    .FailWith("Expected " + Verification.SubjectNameOr("collection") +
                        " to be equal to {0}{reason}, but {1} differs at index {2}.", expected, Subject, index);
            }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中expectedItemsactualItems是你的列表

现在想想在第二次迭代期间(下面的部分)被执行时会发生什么?

actualItems[index].Equals(expectedItems[index])

actualItems[1]原样null,它会抛出空引用异常