Using MSTest how can I verify the exact error message coming from a test method? I know [ExpectedException(typeof(ApplicationException), error msg)]
doesn\'t co
Use this little helper class:
public static class ExceptionAssert
{
public static void Throws(Action action, string message)
where TException : Exception
{
try
{
action();
Assert.Fail("Exception of type {0} expected; got none exception", typeof(TException).Name);
}
catch (TException ex)
{
Assert.AreEqual(message, ex.Message);
}
catch (Exception ex)
{
Assert.Fail("Exception of type {0} expected; got exception of type {1}", typeof(TException).Name, ex.GetType().Name);
}
}
}
Usage:
Foo foo = new Foo();
foo.Property = 42;
ExceptionAssert.Throws(() => foo.DoSomethingCritical(), "You cannot do anything when Property is 42.");
The advantage of explicit catching exceptions is that teh test does not succeed when another member (e.g. during the initialization) throws the exception.