简体   繁体   English

使用 NUnit Assert.Throws 方法或 ExpectedException 属性?

[英]Use NUnit Assert.Throws method or ExpectedException attribute?

I have discovered that these seem to be the two main ways of testing for exceptions:我发现这些似乎是测试异常的两种主要方法:

Assert.Throws<Exception>(()=>MethodThatThrows());

[ExpectedException(typeof(Exception))]

Which of these would be best?其中哪一个最好? Does one offer advantages over the other?一个比另一个有优势吗? Or is it simply a matter of personal preference?或者这只是个人喜好的问题?

The main difference is:主要区别在于:

ExpectedException() attribute makes test passed if exception occurs in any place in the test method.如果在测试方法的任何地方发生异常, ExpectedException()属性会使测试通过。
The usage of Assert.Throws() allows to specify exact place of the code where exception is expected. Assert.Throws()的使用允许指定预期异常的代码的exact位置。

NUnit 3.0 drops official support for ExpectedException altogether. NUnit 3.0 完全放弃了对ExpectedException官方支持。

So, I definitely prefer to use Assert.Throws() method rather than ExpectedException() attribute.所以,我绝对更喜欢使用Assert.Throws()方法而不是ExpectedException()属性。

The first allows you to test for more than one exception, with multiple calls:第一个允许您通过多次调用测试多个异常:

Assert.Throws(()=>MethodThatThrows());
Assert.Throws(()=>Method2ThatThrows());

The second only allows you to test for one exception per test function.第二个只允许您为每个测试函数测试一个异常。

I prefer assert.throws since it allows me to verify and assert other conditions after the exception is thrown.我更喜欢 assert.throws 因为它允许我在抛出异常后验证和断言其他条件。

    [Test]
    [Category("Slow")]
    public void IsValidLogFileName_nullFileName_ThrowsExcpetion()
    {
        var a = new MyTestObject();

        // the exception we expect thrown from the IsValidFileName method
        var ex = Assert.Throws<ArgumentNullException>(() => a.IsValidLogFileName(""));

        // now we can test the exception itself
        Assert.That(ex.Message == "Blah");

    }

您还可以强输入您期望的错误(如旧的 attrib 版本)。

Assert.Throws<System.InvalidOperationException>(() => breakingAction())

If you are using older version( <=2.0 ) of NUnit then you need to use ExpectedException .如果您使用的是旧版本( <=2.0 )的NUnit那么您需要使用ExpectedException

If you are using 2.5 or later version then you can use Assert.Throw()如果您使用的是2.5或更高版本,则可以使用Assert.Throw()

https://github.com/nunit/docs/wiki/Breaking-Changes https://github.com/nunit/docs/wiki/Breaking-Changes

How to use: https://www.nunit.org/index.php?p=exceptionAsserts&r=2.5使用方法: https : //www.nunit.org/index.php?p=exceptionAsserts&r=2.5

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

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