比较具有不同项目类型的集合

Ale*_*mov 3 .net c# bdd unit-testing fluent-assertions

我有两个具有不同项类型的集合,例如:

var collection1 = new List<Type1>();
var collection2 = new List<Type2>();
Run Code Online (Sandbox Code Playgroud)

是否可以使用我自己的相等比较器和FluentAssertions 断言具有不同项类型的两个集合包含任何顺序的相同项

官方FA文档中最相关的示例认为两个集合都是相同的类型:

persistedCustomers.Should().Equal(customers, (c1, c2) => c1.Name == c2.Name);
Run Code Online (Sandbox Code Playgroud)

在我的情况下使用这种方法的一种可能的解决方案是List<Type1>基于来自的项创建新集合collection2并使用它而不是customers在上面的示例中.
但有时它只是不可能,实际上闻起来像是一种开销.

我想知道是否有类似的方法使用像上面的FA优雅,但适合不同项目类型的集合?

更新1(尝试使用@DennisDoomen建议):

让我们来看一个更具体的例子.
假设我们有一个List<DateTime>表示单个月日期的预期值:

    var expectation = new List<DateTime>();
Run Code Online (Sandbox Code Playgroud)

测试方法返回List<int>一天数:

    var actual = new List<int>();
Run Code Online (Sandbox Code Playgroud)

我们想断言测试方法返回的日期数集与期望列表的DateTime.Day值组成的集合相同,即:

    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]);
Run Code Online (Sandbox Code Playgroud)

(但没有排序限制,我不知道如何在这个例子中演示).

我试图以这种方式使用@DennisDoomen建议:

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

问题是,ctx.Expectation这是一种类型int,而不是一种DateTime,所以我DateTime.Day无论如何都无法得到.

我在这里错过了什么?

Den*_*men 5

ShouldBeEquivalentTo是你需要的.默认情况下,它将确保每个集合包含任何顺序在结构上等效的项目.然后,您可以使用Using/ When选项来定义如何Type1Type2应该进行比较.就像是:

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