0

I am trying to use Fluent Assertions on C# outside of test frameworks. Is there any way I could cast an FA check to bool? For example I need to achieve something like:

bool result= a.Should().Be(0);

If passes then result = true; if fails, result = false.

Is there any way of casting or extracting a bool result from the assertion?

greenjaed
  • 589
  • 8
  • 20
kris
  • 3
  • 1
  • 2
  • 3
    Is there a reason you want to use the test framework in your code as opposed to just writing `bool result = a == 0;`? – greenjaed Jun 10 '21 at 18:52
  • Hi greenjaed. It is sort of exercise, where I want to display on concole tests info. As I have tests using XUnit framework, where I used FluertAssertions, it is the easiest way to copy all checks. – kris Jun 12 '21 at 20:46

1 Answers1

2

Fluent Assertions is designed to throw exceptions that testing frameworks catch, not to return values.

About the best you can do is to create a method that accepts an action, and that catches the exception when the action throws. In the catch you'd return false.

public bool Evaluate(Action a)
{
    try
    {
        a();
        return true;
    }
    catch
    {
        return false;
    }
}

You would use it like this:

bool result = Evaluate(() => a.Should().Be(0));

This will have terrible performance in the negative case; throwing exceptions is not cheap. You might get frowns from others because, generally, exceptions shouldn't be used for flow control.

That said, this does what you want.

Kit
  • 20,354
  • 4
  • 60
  • 103
  • Note that this would return false when the delegate throws an exception itself, rather than rethrowing it. – Alejandro Jun 10 '21 at 19:31
  • Yes, that is what the OP wanted -- a `false` value when the assertion failed. – Kit Jun 10 '21 at 19:54
  • Thank you, This answers my question. I just thought they may be built in mechanism I do not know in Fluent Assertions. – kris Jun 10 '21 at 20:13