How to compare lists using fluent-assertions?
Asked Answered
K

2

28

I want to compare a list of objects, ignoring the order of the objects in the list and only comparing some of the properties in the objects, currently I'm using the following code to perform this comparison:

actual.Should().NotBeNull();
actual.Count.Should().Be(expected.Count);
//compare ignoring order
foreach (var exp in expected)
    actual.Should().Contain(act =>
        act.IndividualId.Equals(exp.IndividualId)
        && act.Email.Equals(exp.Email)
        && act.FirstName.Equals(exp.FirstName)
        && act.LastName.Equals(exp.LastName)
    );

However this seems less than ideal, as when there is a failure you do not get a print out of the expected values. Is there a built in mechanism for performing this comparison using fluent assertions?

Kanpur answered 20/3, 2013 at 0:20 Comment(0)
S
20

Not right now. We do have the new equivalency assertion syntax of FA 2.0, but that will also verify if the objects appear in the right order. For FA 2.1 I'm trying to support that, but I'm not sure yet if that will work. It basically means it has to compare the entire object graph behind a collection item with the object graphs for each and every other item in the collection. Surely it will be rather slow.

Sheaves answered 20/3, 2013 at 6:6 Comment(5)
Is it possible say compare two List<string> types using actual.Should().Contain(expected)?Percyperdido
Yes, you can do actual.Should().BeEquivalentTo(expected);Sheaves
for flexibility we usually serialize each object to json then use string compare, the error output looks good to and you never need to update your unit test if someone adds a new propertyDhar
@DennisDoomen, Are there any new approaches in the current FA?Unstudied
In version 2.1 of FA we started to ignore ordering of items by default. Is that what you mean?Sheaves
F
7

In order to assert that a collection of objects is equivalent to another collection of objects, e.g. comparing two List<T>, you can use the BeEquivalentTo() method:

collection.Should().BeEquivalentTo(expectedResult);

Here, I'm using the FluentAssertions nuget package.

Feodora answered 21/6, 2023 at 10:22 Comment(2)
This only works when the two Lists are in the same other....Tapley
@IfeoluwaOsungade According to the documentation, BeEquivalentTo does not check the order: fluentassertions.com/objectgraphs/#ordering My own experience confirms that.Jessikajessup

© 2022 - 2024 — McMap. All rights reserved.