FluentAssessions赢得't排除对象图比较中缺少的成员



我正在尝试使用FluentAssertions对象图比较来比较DTO与其相应的实体。我的实体有一些额外的元数据属性,而我的DTO没有这些属性。

我试图用ExcludingMissingMembers选项排除这些额外的属性,甚至通过明确地排除每个成员本身来排除,如下所示:

result.Entity.Should().BeEquivalentTo(dto, opt => opt
.ExcludingMissingMembers()
.Excluding(x => x.ValidationResult)
.Excluding(x => x.CreatedBy)
.Excluding(x => x.CreatedAt));

但是我的测试一直失败,因为我的DTO没有额外的属性。

消息:预期结果。实体(实体类型(为

实体
{
CreatedAt=<0001-01-01 00:00:00.000>
CreatedBy=
FinancialResourcesOrigins={Labor,Labor}
ProductsOfInterest={FixedIncome,FixedIncome}
ValidationResult=
},但找到

Dto
{
FinancialResourcesOrigins={Labor,Labor}
ProductsOfInterest={FixedIncome,FixedIncome}

配置:

  • 使用声明的类型和成员
  • 按值比较枚举
  • 排除成员ValidationResult
  • 排除成员CreatedBy
  • 排除成员CreatedAt
  • 按名称(或投掷(匹配成员
  • 严格遵守字节数组中项目的顺序
  • 没有自动转换

这里缺少什么?

因此,一个快速测试结果:

var entity = new
{
CreatedAt = DateTime.Now,
CreatedBy = "",
FinancialResourcesOrigins = new[] { "Labor", "Labor" },
ProductsOfInterest = new[] { "FixedIncome", "FixedIncome" },
ValidationResult = ""
};
var dto = new
{
FinancialResourcesOrigins = new[] { "Labor", "Labor" },
ProductsOfInterest = new[] { "FixedIncome", "FixedIncome" },
};

entity.Should()
.BeEquivalentTo(dto, opt => opt
.ExcludingMissingMembers());

这应该如预期的那样起作用。

你的错误似乎是明确的排除,因为成员(你的变量x(是从你的DTO中预期的,而他们不存在

ExcludengMissingMembers((的源代码:

尝试将主题的成员与同名成员匹配关于期望。忽略上不存在的成员期望和以前注册的匹配规则。

在您的场景中"期望";是dto对象,因为entity(主题(具有dto对象的所有属性,所以没有什么可忽略的。

通过切换dtoentity的位置,可以达到预期的效果

dto.Should().BeEquivalentTo(result.Entity, opt => opt.ExcludingMissingMembers());

在切换它们的位置之后,CCD_;期望";并且它在dto(主题(上丢失的属性将被忽略

然而,这种方法使失败的消息有点令人困惑,例如,当result.Entitynull时,消息将是:预期实体为,但发现Dto{..}

Fluent断言6.8.0

actualValue.Should().BeEquivalentTo(expectedValue, options
=> options.Using(new IgnoreNullMembersInExpectation()));
public class IgnoreNullMembersInExpectation : IEquivalencyStep
{
public EquivalencyResult Handle(Comparands comparands, IEquivalencyValidationContext context, IEquivalencyValidator nestedValidator)
{
if(comparands.Expectation is null)
{
return EquivalencyResult.AssertionCompleted;
}
return EquivalencyResult.ContinueWithNext;
}
}

最新更新