FluentAssertions ShouldBeEquivalent 可以与 c#9 记录类型一起使用吗?

Mic*_*pps 8 c# datetime unit-testing fluent-assertions

我一直在摆弄 c#9 的一些新功能,但遇到了一些不那么有趣的事情。如果我尝试在具有 DateTimeOffset 的记录上使用 Should().BeEquivalentTo(),并将 DateTimeOffset 的“使用”选项设置为使用 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;}
   }
Run Code Online (Sandbox Code Playgroud)

Mic*_*pps 7

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

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