Test a method throws a specific exception .NET
How to test tha开发者_JAVA百科t a void method throws a specific exception in .NET.
I have a method that throws 3 different types of exceptions depending on inputs. How would I test that I get the current one each time, AND ALSO test that it doesn't throw any when passed with the correct inputs.
Thanks!
Example in MSTest
[TestMethod]
[ExpectedException(typeof(StackOverflowException))] //Update for your expected Exception Type
public void TestThatExpectsAnExceptionToBeThrown()
{
// Test code here...
}
This requires no assert. If the expected exception is thrown, the test will pass. If not, you've got a failing test. Obviously with the code snippet above you'd substitute the exception type for the type of exception you wish to test for.
If you are using NUnit, you can use the Assert.Throws()
method to test for a specific exception being thrown.
精彩评论