比较 2 个不相同的 DTO,但在 Fluent Assertion 中具有共同的属性

Compare 2 not identical DTO but have common properties in Fluent Assertion

我正在为手动映射器编写单元测试。它将一个对象映射到两个不同的 类 但具有共同的属性。如何比较它们的属性在流利断言中是否相等?

这是我试过的

 var domain = new Domain.ConsentDefinition()
{
     SomeProperty = 1,
     ListOfFirstDTO = new List<FirstDTO>()
     {
          new FirstDTO()
          {
             Name = "Label",
             Age = 18,
          }
     },
     SomeOtherProperty = "one"
}

ef = domain.ToEF();

domain.SomeProperty.Should().Be(ef.SomeProperty);
domain.SomeOtherProperty.Should().Be(ef.SomeOtherProperty);
domain.ListFirstDTO.Should().Equal(ef.ListOfSecondDTO); // This is NOT working

public class FirstDTO
{
   public string Name {get;set;}
   public int Age {get;set;}
}

public class SecondDTO
{
   public string Name {get;set;}
   public int Age {get;set;}
   public string Email {get;set;}
}

覆盖 firstDTO 的 equals,这样您就可以比较值而不是引用:


        public override bool Equals(object obj)
        {
            if (obj == null || !(obj is FirstDTO) || !(obj is SecondDTO))
            {
                return false;
            }
            
            if(obj is SecondDTO){
              return (this.Name == ((SecondDTO)obj).Name)
                && (this.Age == ((SecondDTO)obj).Age)

            }
            // if obj is instance of FirstDTO check the rest of fields...
        }

又是运行

 domain.ListFirstDTO.Should().Equal(ef.ListOfSecondDTO); // This is NOT working

另一个不需要覆盖 equals 的更优雅的解决方案是


domain.ListFirstDTO.Select(c => c.Name).Should().Equal(ef.ListOfSecondDTO.Select(c => c.Name);

domain.ListFirstDTO.Select(c => c.Age).Should().Equal(ef.ListOfSecondDTO.Select(c => c.Age);

fluentassertion/collections

domain.Should().BeEquivalentTo(new
{
   SomeProperty = ef.SomeProperty,
   SomeOtherProperty = ef.SomeOtherProperty,
   ListFirstDTO = ef.ListOfSecondDTO
});

domain.Should().BeEquivalentTo(ef, options => options
  .Including(x => x.SomeProperty)
  .Including(x => x.SomeOtherProperty)
  .Including(x => x.ListOfSecondDTO));

默认情况下,FA 将通过忽略集合中项目的顺序来比较两个集合。使用 WithStrictOrdering 来控制它。

如果第二个 DTO 实现 Equals,那么 FA 将使用它。您可以使用 ComparingByMembers<T> 选项覆盖它。