【问题标题】:Can FluentAssertions ShouldBeEquivalent work with c#9 record types?FluentAssertions ShouldBeEquivalent 可以与 c#9 记录类型一起使用吗?
【发布时间】:2021-01-31 11:01:23
【问题描述】:

我一直在搞乱 c#9 的一些新功能,但我遇到了一些不太有趣的事情。如果我尝试在具有 DateTimeOffset 的记录上使用 Should().BeEquivalentTo(),将 DateTimeOffset 的 Using 选项设置为使用 BeCloseTo,即使 DateTimeOffset 在允许的精度范围内,测试也会失败。有没有办法让它工作(不将记录更改为类哈哈)?非常感谢!

例子:

   public class ExampleTest
   {

      [Fact]
      public void FunWithRecords()
      {
         var thing1 = new Thing
         {
            SomeDate = DateTimeOffset.UtcNow
         };
         var thing2 = new Thing
         {
            SomeDate = DateTimeOffset.UtcNow.AddSeconds(2)
         };
         thing1.Should().BeEquivalentTo(thing2, o =>
            o.Using<DateTimeOffset>(ctx =>
               ctx.Subject.Should().BeCloseTo(ctx.Expectation, 10000))
               .WhenTypeIs<DateTimeOffset>());
      }
   }
   
   public record Thing
   {
      public DateTimeOffset SomeDate {get; init;}
   }

【问题讨论】:

    标签: c# unit-testing datetime fluent-assertions


    【解决方案1】:

    Aaaa 我回答了我自己的问题。这样做:

    thing1.Should().BeEquivalentTo(thing2, o => o
             .ComparingByMembers<Thing>()
             .Using<DateTimeOffset>(ctx => 
                   ctx.Subject.Should().BeCloseTo(ctx.Expectation, 10000)).WhenTypeIs<DateTimeOffset>());
    

    【讨论】:

      【解决方案2】:

      Fluent Assertions 确实支持记录。 它们是编译器生成的“只是”常规类

      • 基于值的相等比较方法
      • GetHashCode() 的覆盖
      • 复制和克隆成员
      • PrintMembers 和 ToString()

      https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#record-types

      默认情况下,BeEquivalentTo 使用 object.Equals 如果覆盖期望类型来比较实例。 当从普通类切换到记录时,类型现在会覆盖 object.Equals,这会改变比较实例的方式。 要覆盖该默认行为,您可以使用ComparingByMembers&lt;T&gt;

      https://fluentassertions.com/objectgraphs/#value-types

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多