5

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
tensorsigma
  • 71
  • 1
  • 4

1 Answers1

4

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

Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
  • 1
    Is there some workaround with Fluent Assertions? Or I have to use cycles in unit tests if I`m sure that nulls are normal for tested collections? – tensorsigma Jan 24 '12 at 16:15
  • for now I would suggest make sure there is no null in collection before calling equal and file a bug on `codeplex` site of `fluentassertion`. Another option could be to download the source and fix it yourself :) – Haris Hasan Jan 24 '12 at 16:18
  • @tensorsigma - I would advise against downloading the source and changing it. Once you start adding in custom fixes you'll be reluctant to download updates to the project, since you'll have to re-add all that stuff. Unless of course the project owners accept your changes and incorporate them into the project code base. – Adam Rackis Jan 24 '12 at 16:24
  • 1
    Fixed in both the 1.7.0 release branch as well as in the trunk. If you want, you can compile an updated version directly from the source code: – Dennis Doomen – Haris Hasan Jan 24 '12 at 19:11