I want to create NUnit test to ensure that my function does not throw an exception. Is there some specific way to do it, or I should just write
[Test] public void noExceptionTest() { testedFunction(); }
and it will succeed if no exception is thrown?
If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.
JUnit provides an option of tracing the exception handling of code. You can test whether the code throws a desired exception or not. The expected parameter is used along with @Test annotation. Let us see @Test(expected) in action.
The ExpectedException rule allows you to verify that your code throws a specific exception.
Advertisements. TestNG provides an option of tracing the exception handling of code. You can test whether a code throws a desired exception or not. Here the expectedExceptions parameter is used along with the @Test annotation.
Assert.DoesNotThrow(() => { /* custom code block here*/});
OR just method
Assert.DoesNotThrow(() => CallMymethod());
For more details see NUnit Exception Asserts
Using NUnit 3.0 Constraint Model type assertions the code would look as follows:
Assert.That(() => SomeMethod(actual), Throws.Nothing);
This example is taken from NUnit wiki.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With