Can FluentAssertions ShouldBeEquivalent work with c#9 record types?
Asked Answered
R

2

8

I've been messing around with some of c#9's new features, and I've run into something that's less than fun. If I try to use Should().BeEquivalentTo() on a record with a DateTimeOffset, setting the Using option for DateTimeOffset to use BeCloseTo, the test fails even if the DateTimeOffset is within the allowed precision. Is there a way to get this to work (without changing the record to a class lol)? Thanks much!

Example:

   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;}
   }
Rudie answered 16/10, 2020 at 22:46 Comment(0)
R
7

Aaaaand I answered my own question. This does the thing:

thing1.Should().BeEquivalentTo(thing2, o => o
         .ComparingByMembers<Thing>()
         .Using<DateTimeOffset>(ctx => 
               ctx.Subject.Should().BeCloseTo(ctx.Expectation, 10000)).WhenTypeIs<DateTimeOffset>());
Rudie answered 17/10, 2020 at 0:51 Comment(0)
A
4

Fluent Assertions does support records. They are "just" regular classes with compiler-generated

  • Methods for value-based equality comparisons
  • Override for GetHashCode()
  • Copy and Clone members
  • PrintMembers and ToString()

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

Per default BeEquivalentTo uses object.Equals if overridden on the expectation type to compare instances. When switching from a plain class to a record, the type now overrides object.Equals which changes the way instances are compared. To override that default behavior you can use ComparingByMembers<T>.

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

Antipus answered 17/10, 2020 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.