Question

FluentAssertions seems to fail with NullReferece exception when I try comparing two collections with nulls

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

        l1.Should().Equal(l2);
    }

Comparison works as expected on collections with no nulls.

Était-ce utile?

La solution

This is happening due to the fact that deep down in the collection comparison logic Fluent Assertion uses following code

 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);
            }

in above code expectedItems and actualItems are your lists

Now think what will happen during second iteration when (part below) will be executed?

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

as actualItems[1] is null so it throws null reference exception

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top