3

I'm writing an Akka.NET Testkit implementation that uses FluentAssertions under the hood, but can't figure out how to write the 'last' Assertion: Equality using a custom Func equality comparer (while getting a nice Error message, of course).

public void AssertEqual<T>(T expected, T actual,
                           Func<T, T, bool> comparer,
                           string format = "", params object[] args)
{
    // This works, but does not give a good message:
    comparer(expected, actual).Should().BeTrue(format, args);

    // But this doesn't work at all:
    // actual.Should().BeEquivalentTo(expected, options => 
             options.Using<T>( x => comparer(x.Subject, expected).Should().BeTrue())
             .WhenTypeIs<T>(),
         format, args);
}

I'm pretty sure there must be some fancy way in FA to do this, but I can't find it.

Bart de Boer
  • 381
  • 2
  • 7

1 Answers1

0

Why don't you replace the call to BeEquivalentTo with a custom assertion built on top of Execute.Assertion as documented in the extensibility section?

Or just use BeEquivalentTo directly using its options? You can even wrap it in your own code like this:

public static void AssertEqual<T>(T actual, T expected,
    Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config)
{
    Func<EquivalencyAssertionOptions<TEvent>, EquivalencyAssertionOptions<TEvent>> effectiveConfig = opt =>
    {
        // customize the assertion in addition to the caller's customization

        return config(opt);
    };

    actual.Should().BeEquivalentTo(expected, effectiveConfig);
}
Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
  • So could I go with just calling Execute.Assertion (I'm implementing a set of Akka TestKit custom assertions - there is no point in making the implementation reusable. ```public void AssertEqual(T expected, T actual, Func comparer, string format = "", params object[] args) { Execute.Assertion .BecauseOf(format, args) .ForCondition(comparer(expected, actual)) .FailWith($"{typeof(T).Name} was expected to be equal to `{expected}` (using a custom comparison), but was `{actual}` instead"); }``` – Bart de Boer Jun 07 '18 at 06:42
  • If you wrap the `Func` with an `Expression`, FA will format it into something readable (mostly). – Dennis Doomen Jun 07 '18 at 08:36
  • Exactly what my colleague https://stackoverflow.com/users/74198/bas-bossink suggested indeed. I'll try! – Bart de Boer Jun 07 '18 at 09:18