我有两个具有不同项类型的集合,例如:
var collection1 = new List<Type1>();
var collection2 = new List<Type2>();
是否可以使用我自己的相等比较器和FluentAssertions断言具有不同项类型的两个集合包含任何顺序的相同项?
来自the official FA documentation的最相关的例子认为两个集合都是相同的类型:
persistedCustomers.Should().Equal(customers, (c1, c2) => c1.Name == c2.Name);
在我的情况下使用这种方法的一种可能的解决方案是基于来自List<Type1>
的项目创建新的collection2
集合,并在上面的示例中使用它而不是customers
。
但有时它只是不可能,实际上闻起来像是一种开销。
我想知道是否有类似的方法使用像上面的FA优雅,但适合不同项目类型的集合?
更新1(尝试使用@DennisDoomen建议):
让我们来看一个更具体的例子。
假设我们有一个List<DateTime>
的预期值,代表一个月的日期:
var expectation = new List<DateTime>();
测试方法返回日期数字的List<int>
:
var actual = new List<int>();
我们想断言测试方法返回的日期数集与期望列表的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]);
(但没有排序限制,我不知道如何在这个例子中演示)。
我试图以这种方式使用@DennisDoomen建议:
actual.ShouldBeEquivalentTo(
expectation,
options => options.Using<int>(
ctx => ctx.Subject.Should().Be(ctx.Expectation.Day)).WhenTypeIs<int>());
问题是ctx.Expectation
这里是一种int
,而不是DateTime
,所以无论如何我不能得到DateTime.Day
。
我在这里错过了什么?
ShouldBeEquivalentTo
是你需要的。默认情况下,它将确保每个集合包含任何顺序在结构上等效的项目。然后,您可以使用Using
/ When
选项来定义如何比较Type1
和Type2
。就像是:
collection1.ShouldBeEquivalentTo(collection2, options => options
.Using<Type1>(t1 => ctx.Subject.Should().Be(ctx.Expectation)
.WhenTypeIs<Type1>();