kris
kris

Reputation: 33

C# fluent assertions result of check as bool

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?

Upvotes: 3

Views: 5039

Answers (1)

Kit
Kit

Reputation: 21699

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.

Upvotes: 4

Related Questions