Created
October 25, 2012 20:35
-
-
Save taeber/3955229 to your computer and use it in GitHub Desktop.
xUnit.net inspired ExpectedExceptionAttribute alternative for MSTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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