简体   繁体   English

C# 流利断言检查结果为 bool

[英]C# fluent assertions result of check as bool

I am trying to use Fluent Assertions on C# outside of test frameworks.我正在尝试在测试框架之外的 C# 上使用流利断言。 Is there any way I could cast an FA check to bool?有什么办法可以将 FA 检查设为 bool 吗? For example I need to achieve something like:例如,我需要实现以下目标:

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

If passes then result = true;如果通过则结果 = true; if fails, result = false.如果失败,则结果 = 假。

Is there any way of casting or extracting a bool result from the assertion?有没有办法从断言中转换或提取bool结果?

Fluent Assertions is designed to throw exceptions that testing frameworks catch, not to return values. Fluent Assertions 旨在抛出测试框架捕获的异常,而不是返回值。

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 .catch你会返回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.也就是说,这就是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM