Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created November 28, 2010 07:34
Show Gist options
  • Save beccasaurus/718696 to your computer and use it in GitHub Desktop.
Save beccasaurus/718696 to your computer and use it in GitHub Desktop.
NUnit AssertThrows() ... when [ExpectedException] won't work for you
// NOTE: Yes, NUNit has an [ExpectedException] attribute, but:
// - Sometimes I want to have a few assertions in the same [Test]
// - AssertThrows(() => { code }) is nicer than ExpectedException, IMHO
//
// NOTE: This is implemented as extension methods so it doesn't matter what
// class your NUnit tests are in ... if you don't want to have to say
// this.AsserThrows() (instead of just AssertThrows), you could add
// these methods to a baseclass that your [TestFixture] classes inherit from.
// Usage:
//
// this.AssertThrows(...)
//
public static class AssertThrowsExtension {
// AssertThrows<SpecialException>(() => { ... })
public static void AssertThrows<T>(this object o, Action action) {
o.AssertThrows<T>(action);
}
// AssertThrows<SpecialException>("BOOM!", () => { ... })
public static void AssertThrows<T>(this object o, string messagePart, Action action) {
o.AssertThrows(action, messagePart, typeof(T));
}
// AssertThrows("BOOM!", () => { ... })
public static void AssertThrows(this object o, string messagePart, Action action) {
o.AssertThrows(action, messagePart);
}
// AssertThrows(() => { ... })
// AssertThrows(() => { ... }, "BOOM!") // <--- AssertThrows(Message, Action) is preferred
// AssertThrows(() => { ... }, "BOOM!", typeof(SpecialException)) // <--- AssertThrows<T>(Message) is preferred
public static void AssertThrows(this object o, Action action, string messagePart = null, Type exceptionType = null) {
try {
action.Invoke();
Assert.Fail("Expected Exception to be thrown, but none was.");
} catch (Exception ex) {
// NOTE: Sometimes, this might be a TargetInvocationException, in which case
// the *actual* exception thrown will be ex.InnerException.
// If I run into that circumstance again, I'll update the code to reflect this.
// check exception type, if provided
if (exceptionType != null)
if (!exceptionType.IsAssignableFrom(ex.GetType()))
Assert.Fail("Expected Exception of type {0} to be thrown, but got an Exception of type {1}", exceptionType, ex.GetType());
// check exception message part, if provided
if (messagePart != null)
if (! ex.Message.Contains(messagePart))
Assert.Fail("Expected {0} Exception to be thrown with a message containing {1}, but message was: {2}",
exceptionType, messagePart, ex.Message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment