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.
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>
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.