Comparing collections with different item types

I have two collections with different types of elements, for example:

var collection1 = new List<Type1>();
var collection2 = new List<Type2>();

      

Is it safe to say that two collections with different element types contain the same elements in any order using my own comparison matcher with FluentAssertions?

The most related example from the official FA documentation believes that both collections are of the same type:

persistedCustomers.Should().Equal(customers, (c1, c2) => c1.Name == c2.Name);

      

One possible solution to use this approach for my situation is to create a new collection List<Type1>

based on items from collection2

and use that instead customers

in the example above.
But sometimes it's just not possible and really smells like overhead.

I am wondering if there is a similar approach that uses the FA elegance as above, but is suitable for collections with different types of items?

UPDATE 1 (Trying to use @ DennisDoomen's suggestion):

Let's look at a more specific example.
Let's assume we have List<DateTime>

expected values ​​that represent dates from one month:

    var expectation = new List<DateTime>();

      

The testing method returns List<int>

daily numbers:

    var actual = new List<int>();

      

We want to argue that the set of day numbers returned by the test method is the same as the set of waitlist DateTime.Day values, that is:

    Assert.AreEqual(expectation[0].Day, actual[0]);
    Assert.AreEqual(expectation[1].Day, actual[1]);
...
    Assert.AreEqual(expectation[expectation.Count - 1].Day, actual[actual.Count - 1]);

      

(but without the ordering constraint, which I am not demonstrating in this example).

I'm trying to use @DennisDoomen's suggestion like this:

    actual.ShouldBeEquivalentTo(
        expectation,
        options => options.Using<int>(
            ctx => ctx.Subject.Should().Be(ctx.Expectation.Day)).WhenTypeIs<int>());

      

The problem is that ctx.Expectation

here is the type int

and not DateTime

, so I can't get it DateTime.Day

anyway.

What am I missing here?

+3


source to share


1 answer


ShouldBeEquivalentTo

- This is what you need. By default, it ensures that each collection contains elements that are structurally equivalent in any order. Then you can use the parameters Using

/ When

, to determine how to compare Type1

and Type2

. Something like:



collection1.ShouldBeEquivalentTo(collection2, options => options 
   .Using<Type1>(t1 => ctx.Subject.Should().Be(ctx.Expectation) 
   .WhenTypeIs<Type1>(); 

      

+5


source







All Articles