Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test with NO expected exception

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?

like image 901
Yury Pogrebnyak Avatar asked Mar 21 '12 11:03

Yury Pogrebnyak


People also ask

How do you test for no exception 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.

How can you use JUnit for testing a code that throws a desired exception?

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.

What is expected exception?

The ExpectedException rule allows you to verify that your code throws a specific exception.

What is exception testing?

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.


2 Answers

Assert.DoesNotThrow(() => { /* custom code block here*/}); 

OR just method

Assert.DoesNotThrow(() => CallMymethod()); 

For more details see NUnit Exception Asserts

like image 161
sll Avatar answered Sep 28 '22 10:09

sll


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.

like image 28
Jack Ukleja Avatar answered Sep 28 '22 10:09

Jack Ukleja