Fluent Assertions - Overriding comparison in ShouldBeEquivalentTo()

3.7k views Asked by At

I have the following DTO:

public class Dto
{
    public DateTime Date { get; set; }
}

And I'm trying to override the comparison of a property using this syntax as per the FA wiki:

public void Override_test()
{
    // Arrange
    var actual = new Dto { Date = DateTime.Now };
    var expected = new Dto { Date = DateTime.Now };

    // Act

    // Assert
    actual.ShouldBeEquivalentTo(expected, options => 
        options.Using<DateTime>(x => x.Subject.Should().BeCloseTo(DateTime.Now)));
}

But the test does not compile. I get this error:

Cannot implicitly convert type 'FluentAssertions.Equivalency.EquivalencyAssertionOptions<FluentAssertions.ShouldBeEquivalentTo.Override.Dto>.Restriction<System.DateTime>' to 'FluentAssertions.Equivalency.EquivalencyAssertionOptions<FluentAssertions.ShouldBeEquivalentTo.Override.Dto>'

Can anyone advise the correct syntax?

1

There are 1 answers

1
Dennis Doomen On BEST ANSWER

You have to tell FA when to use that Using construction using the WhenTypeIs<DateTime>(). In other words:

actual.ShouldBeEquivalentTo(expected, options => 
    options.Using<DateTime>(x => x.Subject.Should().BeCloseTo(DateTime.Now)).WhenTypeIs<DateTime>());

However, I would suggest not to rely on DateTime.Now too much. Instead, consider using something like Ayende Rahien has proposed in this article.