簡體   English   中英

NUnit斷言沒有引發特定異常

[英]NUnit assertion that a certain exception is not thrown

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

我該如何創建它,或使用約束機制來做到這一點?

也許可以這樣實現:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM