Skip to content

Instantly share code, notes, and snippets.

@gilles-leblanc
Created January 26, 2014 20:47
Show Gist options
  • Save gilles-leblanc/8639247 to your computer and use it in GitHub Desktop.
Save gilles-leblanc/8639247 to your computer and use it in GitHub Desktop.
A better alternative than using the ExpectedException attribute for catching exceptions in C#.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TestUtilities
{
public static class AssertExtension
{
public static T Throws<T>(Action expressionUnderTest, string exceptionMessage = "Expected exception has not been thrown by target of invocation.") where T : Exception
{
try
{
expressionUnderTest();
}
catch (T exception)
{
return exception;
}
Assert.Fail(exceptionMessage);
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment