Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use NUnit Assert.Throws method or ExpectedException attribute?

I have discovered that these seem to be the two main ways of testing for exceptions:

Assert.Throws<Exception>(()=>MethodThatThrows());

[ExpectedException(typeof(Exception))]

Which of these would be best? Does one offer advantages over the other? Or is it simply a matter of personal preference?

like image 783
SamuelDavis Avatar asked Oct 14 '22 18:10

SamuelDavis


People also ask

How do I use Assert in NUnit?

Apply a constraint to an actual value, succeeding if the constraint is satisfied and throwing an assertion exception on failure. Asserts that a condition is true. If the condition is false the method throws an AssertionException. Asserts that a condition is true.

How do I throw an exception in NUnit?

Throws "attempts to invoke a code snippet, represented as a delegate, in order to verify that it throws a particular exception." The () => DoSomething() syntax represents a lambda, essentially an anonymous method. So in this case, we are telling Assert. Throws to execute the snippet o. Foo() .

How do you throw Assert?

So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert. Throws assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.

What is the use of test attribute NUnit?

The Test attribute is one way of marking a method inside a TestFixture class as a test. It is normally used for simple (non-parameterized) tests but may also be applied to parameterized tests without causing any extra test cases to be generated. See Parameterized Tests for more info.


1 Answers

The main difference is:

ExpectedException() attribute makes test passed if exception occurs in any place in the test method.
The usage of Assert.Throws() allows to specify exact place of the code where exception is expected.

NUnit 3.0 drops official support for ExpectedException altogether.

So, I definitely prefer to use Assert.Throws() method rather than ExpectedException() attribute.

like image 269
Alexander Stepaniuk Avatar answered Oct 17 '22 07:10

Alexander Stepaniuk