Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentAssertions Should.Equal on collections, containing nulls

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.

like image 567
tensorsigma Avatar asked Oct 09 '22 22:10

tensorsigma


1 Answers

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

like image 176
Haris Hasan Avatar answered Oct 12 '22 12:10

Haris Hasan