NUnit Exception Handling: Assert.Throws vs ExpectedException Attribute

When it comes to unit testing in NUnit, handling exceptions is an important aspect to consider. There are two ways to handle exceptions in NUnit: Assert.Throws and ExpectedException Attribute.

Índice
  1. Assert.Throws
  2. ExpectedException Attribute
  3. Which one to use?

Assert.Throws

Assert.Throws is a method provided by NUnit that allows us to handle exceptions in our unit tests. It takes two parameters: the type of exception we expect to be thrown and a delegate that contains the code we want to test. If the delegate throws an exception of the expected type, the test passes. If it throws an exception of a different type or no exception at all, the test fails.

<test>
  <code>
    Assert.Throws<ArgumentNullException>(() => MethodThatThrowsArgumentNullException(null));
  </code>
</test>

ExpectedException Attribute

The ExpectedException Attribute is another way to handle exceptions in NUnit. It is an attribute that we apply to our test method and specifies the type of exception we expect to be thrown. If the test method throws an exception of the expected type, the test passes. If it throws an exception of a different type or no exception at all, the test fails.

<test>
  <attributes>
    ExpectedException(typeof(ArgumentNullException))
  </attributes>
  <code>
    MethodThatThrowsArgumentNullException(null);
  </code>
</test>

Which one to use?

Both Assert.Throws and ExpectedException Attribute can be used to handle exceptions in NUnit. The choice between the two is a matter of personal preference and coding style. However, Assert.Throws is generally considered to be more flexible and easier to read, as it allows us to specify the exact line of code that should throw the exception.

Overall, when it comes to handling exceptions in NUnit, both Assert.Throws and ExpectedException Attribute are viable options. It is up to the developer to choose the one that best fits their needs and coding style.

Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information