Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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