Edit :
MS Test Framework belatedly has copied other Unit test frameworks and does now have Assert.ThrowsException
and Assert.ThrowsExceptionAsync
which behave similar to the NUnit equivalents.
However, at time of writing, there is still no direct equivalent of Assert.Catch<TException>
which allows testing for TException
or a subclass of TException
, so your unit tests will need to be exact about the setup and exeptions which are tested. From MS Test Docs:
Tests whether the code specified by delegate action throws exact given exception of type T (and not of derived type) and throws AssertFailedException if code does not throws exception or throws exception of type other than T.
Prior to SDK 2017
MS needs to catch up to features available in other testing frameworks. e.g. As of v 2.5, NUnit has the following method-level Assert
s for testing exceptions:
Assert.Throws, which will test for an exact exception type:
Assert.Throws<NullReferenceException>(() => someNullObject.ToString());
And Assert.Catch
, which will test for an exception of a given type, or an exception type derived from this type:
Assert.Catch<Exception>(() => someNullObject.ToString());
As an aside, when debugging unit tests which throw exceptions, you may want to prevent VS from breaking on the exception.
Edit
Just to give an example of Matthew's comment below, the return of the generic Assert.Throws
and Assert.Catch
is the exception with the type of the exception, which you can then examine for further inspection:
// The type of ex is that of the generic type parameter (SqlException)
var ex = Assert.Throws<SqlException>(() => MethodWhichDeadlocks());
Assert.AreEqual(1205, ex.Number);