测试方法会抛出特定的异常.NET

Sco*_*ott 2 unit-testing assert mstest exception-handling

如何测试void方法在.NET中引发特定异常.

我有一个方法,根据输入抛出3种不同类型的异常.我如何测试我每次都获得当前的一个,并且还测试它在通过正确输入时不会抛出任何内容.

谢谢!

Fin*_*las 12

MSTest中的示例

[TestMethod]
[ExpectedException(typeof(StackOverflowException))]  //Update for your expected Exception Type
public void TestThatExpectsAnExceptionToBeThrown()
{
   // Test code here...
}
Run Code Online (Sandbox Code Playgroud)

这不需要断言.如果抛出预期的异常,则测试将通过.如果没有,你的测试失败了.显然,使用上面的代码片段,您可以将异常类型替换为您要测试的异常类型.