Craig Curtis
Craig Curtis

Reputation: 863

Testing list equivalency by including properties in nested lists using Fluent Assertions

Is there a way to assert the equivalency of two lists of objects by properties located in a nested list? I know you can test equivalency with ShouldAllBeEquivalentTo() and Include() only certain properties, but I would like to call Include() on a property defined in a nested list:

class A
{
    public B[] List { get; set; }
    public string SomePropertyIDontCareAbout { get; set; }
}

class B
{
    public string PropertyToInclude { get; set; }
    public string SomePropertyIDontCareAbout { get; set; }
}

var list1 = new[]
{
    new A
    {
        List = new[] {new B(), new B()}
    },
};
var list2 = new[]
{
    new A
    {
        List = new[] {new B(), new B()}
    },
};

list1.ShouldAllBeEquivalentTo(list2, options => options
    .Including(o => o.List.Select(l => l.PropertyToInclude))); // doesn't work

Upvotes: 0

Views: 738

Answers (1)

Jonas Nyrup
Jonas Nyrup

Reputation: 2586

Currently there isn't an idiomatic way to achieve this, but the API is flexible enough to do it, albeit in a more clumpsy way.

There is an open issue about this problem, which also lists some solutions.

With the current API (version 5.7.0), your posted example can be asserted by only including the property List, and then excluding properties ending with "SomePropertyIDontCareAbout".

var list1 = new[]
{
    new A
    {
        SomePropertyIDontCareAbout = "FOO",
        List = new[]
        {
            new B()
            {
                PropertyToInclude = "BAR",
                SomePropertyIDontCareAbout = "BAZ"
            },
        }
    },
};

var list2 = new[]
{
    new A
    {
        SomePropertyIDontCareAbout = "BOOM",
        List = new[]
        {
            new B()
            {
                PropertyToInclude = "BAR",
                SomePropertyIDontCareAbout = "BOOM"
            },
        }
    },
};

// Assert
list1.Should().BeEquivalentTo(list2, opt => opt
    .Including(e => e.List)
    .Excluding(e => e.SelectedMemberPath.EndsWith(nameof(B.SomePropertyIDontCareAbout))));

Upvotes: 1

Related Questions