Search code examples
c#unit-testingfluent-assertions

Asserting a collection of objects is a part of another collection of objects of the same type


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?


Solution

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