Search code examples
c#unit-testingfluent-assertions

Fluent Assertions ShouldAllBeEquivalentTo


I'm not sure if an old version of FluentAssertions had this or not but I'd like to compare a collection to another collection. I have a dto like so:

public class UserDTO
{
    public int Id { get; set; }
    public string Username { get; set; }
}

I have two lists Id like to compare.

 List<UserDTO> createdUsers = this.GetCreatedUser();
 var expectedResults = this.dbContext.Users.Top(10);

The closest thing I see to should all be equivalent is:

 createdUsers.Should().AllBeEquivalentTo(expectedResults)

but when I try to pass my exclusions, it seems to be operating providing me exlusions for the list instead of the entity itself.

I would like to compare two list of these excluding the Id property. I could of sworn there was a function called ShouldAllBeEquivalentTo which took in options to allow exluding,

createdUsers.ShouldAllBeEquivalentTo(expectedResults, o => o.Excluding(x => x.Id);

How can I compare collections while excluding properties in the comparison?


Solution

  • Documentation suggests the following when it comes to exclusions with Collections and Dictionaries

    createdUsers.Should().BeEquivalentTo(expectedResults, options => options.Excluding(_ => _.Id));
    

    Quote from documentation:

    to assert that all instances of OrderDto are structurally equal to a single object:

    orderDtos.Should().AllBeEquivalentTo(singleOrder);
    

    Reference Object graph comparison: Collections and Dictionaries