不抛出某个异常的NUnit断言

本文关键字:NUnit 断言 异常 | 更新日期: 2023-09-27 18:05:35

NUnit有这些:

Exception Assert.Throws<TActual>(TestDelegate)        // code must throw a TActual
void Assert.DoesNotThrow(TestDelegate)                // code mustn't throw anything

没有:

Exception Assert.DoesNotThrow<TActual>(TestDelegate)  // code musn't throw a TActual, but 
                                                      // is allowed to throw anything else

我如何创建它,或者使用约束机制来做到这一点?

不抛出某个异常的NUnit断言

也许你可以这样实现:

public static class CustomAssert
{
    public static void DoesNotThrow<T>(TestDelegate code) where T : Exception
    {
        DoesNotThrow<T>(code, string.Empty, null);
    }
    public static void DoesNotThrow<T>(TestDelegate code, string message, params object[] args) where T : Exception
    {
        Assert.That(code, new ThrowsNotExceptionConstraint<T>(), message, args);
    }
}
public class ThrowsNotExceptionConstraint<T> : ThrowsExceptionConstraint where T : Exception
{
    public override string Description
    {
        get { return string.Format("throw not exception {0}", typeof(T).Name); }
    }
    public override ConstraintResult ApplyTo<TActual>(TActual actual)
    {
        var result = base.ApplyTo<TActual>(actual);
        return new ThrowsNotExceptionConstraintResult<T>(this, result.ActualValue as Exception);
    }
    protected override object GetTestObject<TActual>(ActualValueDelegate<TActual> del)
    {
        return new TestDelegate(() => del());
    }
    class ThrowsNotExceptionConstraintResult<T> : ConstraintResult where T : Exception
    {
        public ThrowsNotExceptionConstraintResult(ThrowsNotExceptionConstraint<T> constraint, Exception caughtException)
            : base(constraint, caughtException, !(caughtException is T)) { }
        public override void WriteActualValueTo(MessageWriter writer)
        {
            if (this.Status == ConstraintStatus.Failure)
                writer.Write("throws exception {0}", typeof(T).Name);
            else
                base.WriteActualValueTo(writer);
        }
    }
}

并将其命名为

CustomAssert.DoesNotThrow<TException>(() => { throw new TException(); });

我没有使用NUnit,所以也许有更好的方法

如果您找不到更简洁的解决方案,您可以这样做:

[Test]
public void TestThatMyExceptionWillNotBeThrown()
{
    try
    {
        TheMethodToTest();
        // if the method did not throw any exception, the test passes
        Assert.That(true);
    }
    catch(Exception ex)
    {
        // if the thrown exception is MyException, the test fails
        Assert.IsFalse(ex is MyException);
    }
}