NUnit 检查调用不会使用流畅的断言抛出

NUnit check a call does not throw using fluent assertions

我开发了一个带有签名 void ThrowIfAny<T>(this IEnumerable<T> e, Func<T, bool> f) 的扩展方法,我正在对其进行单元测试。从逻辑上讲,其中一项测试是检查不抛出。我知道我可以这样写断言:

Assert.DoesNotThrow(() => anEnum.ThrowIfAny(t => false));

但是,我在其余的单元测试中使用基于约束的断言,我想知道这个断言是否可以使用这种风格编写,也许是这样的(它不编译) :

Assert.That(() => anEnum.ThrowIfAny(t => false), Does.Not.Throw);

您基本上需要编写扩展来帮助您做到这一点。我通常使用 CAssert 名称编写多个 Assert 扩展:

public static class CAssert
{
    public static void That(Action action, MyTestSuit suit)
    {
        try
        {
            action();
            if(suit.ShouldThrow)
            {
                Assert.Fail("Not thrown any exception but expected to.")
            }
        }
        catch(Exception e)
        {
            if(suit.ShouldNotThrow)
            {
                Assert.Fail("Exception was thrown but not expected.")
            }
        }
    }
}

测试服基本上是一组选项。它主要是单身人士。您可以根据需要重载它的运算符,例如组合不同花色的选项:

CAssert.That(()=> 1/0, Throws.Error<DivideByZeroException>() | Throws.Error<ArithmeticException>());

应该这样做:

Assert.That(() => anEnum.ThrowIfAny(t => false), Throws.Nothing);

ThrowsNothingContraint