Search code examples
c#unit-testingexceptionmstestassert

MSTest ThrowsException with conditions on the exception object?


I'm using MSTest Assert.ThrowsException, but sometimes I want to add test conditions on the thrown exception object, e.g. checking that the message mentions a specific phrase, identifier, data value or whatever.

The best solution I've found is a construct that doesn't use Assert.ThrowsException, but resorts to try...catch:

bool success = false;
try
{
    // Code to be tested goes here...
    success = true;
}
catch (Exception e)
{
    Assert.IsInstanceOfType(e, typeof(DesiredExceptionClass));
    // Tests on e go here...
}
if (success)
    Assert.Fail($"Should have thrown {nameof(DesiredExceptionClass)}.");

Is there a better way?

With "better" i mean more readable, compacter code, with less "boilerplate".


Solution

  • I'm using this way:

        Exception exception = null;
            try
            {
                // Code to be tested goes here...
            }
            catch (Exception e)
            {
                exception = e;
            }
            Assert.IsInstanceOfType(exception, typeof(DesiredExceptionClass));