NUnit的ExpectedExceptionAttribute是否只能测试是否会引发异常?

Dar*_*zak 5 c# nunit exception

我是C#和NUnit的全新人物.

在Boost.Test中有一系列BOOST_*_THROW宏.在Python的测试模块中有TestCase.assertRaises方法.

据我所知,在C#中使用NUnit(2.4.8)进行异常测试的唯一方法就是使用ExpectedExceptionAttribute.

为什么我更喜欢ExpectedExceptionAttribute- 比如说 - Boost.Test的方法?这个设计决定背后有什么推理?为什么在C#和NUnit的情况下会更好?

最后,如果我决定使用ExpectedExceptionAttribute,在引发异常并获取异常后,如何进行一些额外的测试?假设我想测试需求,说明在一些setter引发之后对象必须是有效的System.IndexOutOfRangeException.您将如何修复以下代码以按预期编译和工作?

[Test]
public void TestSetterException()
{
    Sth.SomeClass obj = new SomeClass();

    // Following statement won't compile.
    Assert.Raises( "System.IndexOutOfRangeException",
                   obj.SetValueAt( -1, "foo" ) );

    Assert.IsTrue( obj.IsValid() );
}
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢你的回答.今天,我发现了一个It's Tests 博客文章,其中提到了你描述的所有三种方法(还有一个小的变化).遗憾的是我以前找不到它:-(.

Jon*_*eet 13

我很惊讶我还没有看到这种模式.David Arno非常相似,但我更喜欢这种简单:

try
{
    obj.SetValueAt(-1, "foo");
    Assert.Fail("Expected exception");
}
catch (IndexOutOfRangeException)
{
    // Expected
}
Assert.IsTrue(obj.IsValid());
Run Code Online (Sandbox Code Playgroud)


Cri*_*rdo 10

如果你可以使用NUnit 2.5,那里有一些不错的助手.

Assert.That( delegate { ... }, Throws.Exception<ArgumentException>())
Run Code Online (Sandbox Code Playgroud)