NUnit断言不抛出某个异常

时间:2016-09-05 08:56:36

标签: c# nunit

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

我怎样才能创建它,或使用约束机制来做到这一点?

2 个答案:

答案 0 :(得分:3)

也许你可以像这样实现它:

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,所以也许有更好的方法。

答案 1 :(得分:1)

如果找不到任何清洁解决方案,可以执行以下操作。

[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);
    }
}