Skip to content

Instantly share code, notes, and snippets.

@DavidRogersDev
Created June 22, 2014 00:23
Show Gist options
  • Save DavidRogersDev/394384a4f477dd107996 to your computer and use it in GitHub Desktop.
Save DavidRogersDev/394384a4f477dd107996 to your computer and use it in GitHub Desktop.
ExceptionAssert includes a Throws static method which is meant to replace the usage of the ExpectedException attribute as a more targeted way of testing for an exception.
public static class ExceptionAssert
{
public static void Throws<T>(Action code, string exceptionMessage = null, string message = null, params object[] args) where T : Exception
{
try
{
code.Invoke();
Assert.Fail("No exception was thrown by the code under test.");
}
catch (Exception exception)
{
if (string.IsNullOrWhiteSpace(exceptionMessage))
{
Assert.AreEqual(exception.GetType(), typeof(T), message, args);
}
else
{
Assert.AreEqual(exception.GetType(), typeof(T), message, args);
Assert.IsTrue(exception.Message.StartsWith(exceptionMessage, StringComparison.OrdinalIgnoreCase));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment