Skip to content

Instantly share code, notes, and snippets.

@taeber
Created October 25, 2012 20:35
Show Gist options
  • Save taeber/3955229 to your computer and use it in GitHub Desktop.
Save taeber/3955229 to your computer and use it in GitHub Desktop.
xUnit.net inspired ExpectedExceptionAttribute alternative for MSTest
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTests
{
/// <summary>
/// Fluent interface for expected exceptions.
/// </summary>
/// <example>
/// Expect.Exception(() => DoSomethingBad())
/// .OfExactType<CriticalException>()
/// .WithMessage("You can't build there.");
/// </example>
/// <example>
/// Expect.Exception(delegate
/// {
/// DoSomethingBad();
/// });
/// </example>
public class Expect
{
public delegate void ThrowsDelegate();
public static Expect Exception(ThrowsDelegate testCode)
{
try
{
testCode();
Assert.Fail();
}
catch (Exception actual)
{
return new Expect(actual);
}
// ReSharper disable HeuristicUnreachableCode
// Heuristically unreachable, but compiler required.
return null;
// ReSharper restore HeuristicUnreachableCode
}
private readonly Exception _actualException;
protected Expect(Exception actual)
{
_actualException = actual;
}
public virtual Expect WithMessage(string expectedMessage)
{
Assert.IsNotNull(_actualException);
Assert.AreEqual(expectedMessage, _actualException.Message);
return this;
}
public virtual Expect OfType<TException>()
where TException : Exception
{
Assert.IsNotNull(_actualException);
Assert.IsInstanceOfType(_actualException, typeof(TException));
return this;
}
public virtual Expect OfExactType<TException>()
where TException : Exception
{
Assert.IsNotNull(_actualException);
Assert.AreEqual(typeof(TException), _actualException.GetType());
return this;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment