160

我发现这些似乎是测试异常的两种主要方法:

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

[ExpectedException(typeof(Exception))]

其中哪一个最好?一个比另一个有优势吗?还是仅仅是个人喜好问题?

4

5 回答 5

266

主要区别在于:

ExpectedException()如果测试方法中的任何地方发生异常,属性使测试通过。
的使用Assert.Throws()允许指定exact预期异常的代码位置。

NUnit 3.0 完全放弃了官方支持ExpectedException

所以,我绝对更喜欢使用Assert.Throws()方法而不是ExpectedException()属性。

于 2013-02-23T18:01:27.977 回答
100

第一个允许您通过多个调用测试多个异常:

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

第二个只允许您为每个测试函数测试一个异常。

于 2013-02-21T23:59:53.100 回答
46

我更喜欢 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");

    }
于 2013-02-22T00:02:51.430 回答
12

您也可以强输入您期望的错误(如旧的属性版本)。

Assert.Throws<System.InvalidOperationException>(() => breakingAction())
于 2015-11-24T12:23:41.370 回答
1

如果您使用的是旧版本(<=2.0),NUnit那么您需要使用ExpectedException.

如果您使用的是2.5或更高版本,则可以使用Assert.Throw()

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

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

于 2017-03-22T06:38:11.113 回答