0

I'm trying to use .BeSubsetOf() from Fluent Assertions to ensure that one collection of objects is a subset of another, bigger collection of objects of the same type, but the assertion always fails.

Example code:

    var expected = new[]
    {
        new Campus
        {
            Id = 1,
            Name = "Campus 1"
        },

        new Campus
        {
            Id = 2,
            Name = "Campus 2"
        },

        new Campus
        {
            Id = 3,
            Name = "Campus 3"
        }
    };

    var actual = new[]
    {
        new Campus
        {
            Id = 1,
            Name = "Campus 1"
        },

        new Campus
        {
            Id = 2,
            Name = "Campus 2"
        }
    };

    actual.Should().BeSubsetOf(expected);

What's wrong here?

YMM
  • 632
  • 1
  • 10
  • 21
  • This is probably because it's defaulting to reference equality. There should be an overload to do your own comparison. https://fluentassertions.com/objectgraphs/ – gunr2171 Jan 27 '22 at 19:58

1 Answers1

2

That is happening because BeSubsetOf use the object's .Equals method for comparison.

One option is to override .Equals method of the type you are comparing.

Second alternative can be to verify one object at the time

foreach (var campus in actual)
{
   expected.Should().ContainEquivalentOf(campus);
}
Fabio
  • 31,528
  • 4
  • 33
  • 72