Assert.Throws Method (NUnit 2.5)

Preliminary documentation, subject to change.

The Assert.Throws method is pretty much in a class by itself. Rather than comparing values, it attempts to invoke a code snippet, represented as a delegate, in order to verify that it throws a particular exception.

Assert.Throws provides both a non-generic and (in the .NET 2.0 version) a generic syntax.


Assert.Throws( Type expectedExceptionType, TestSnippet code );
Assert.Throws( Type expectedExceptionType, TestSnippet code, 
		string message );
Assert.Throws( Type expectedExceptionType, TestSnippet code, 
		string message, params object[] parms);

Assert.Throws<T>( TestSnippet code );
Assert.Throws<T>( TestSnippet code, string message );
Assert.Throws<T>( TestSnippet code, string message, 
		params object[] parms);
		

In the above code TestSnippet is a delegate of the form void TestSnippet(), which is used to execute the code in question. Under .NET 2.0, this may be an anonymous delegate.

The following example shows four equivalent ways of writing the same test. All of them except the first require .NET 2.0.

[TestFixture]
public class AssertThrowsTests
{
  [Test]
  public void Tests()
  {
    Assert.Throws( typeof(ArgumentException),
      new TestSnippet(MethodThatThrows) );
	  
    Assert.Throws<ArgumentException>(
      new TestSnippet(MethodThatThrows) );
	  
    Assert.Throws( typeof(ArgumentException),
      delegate { throw new ArgumentException() } );
	  
    Assert.Throws<ArgumentException>(
      delegate { throw new ArgumentException() } );
  }
  
  void MethodThatThrows()
  {
    throw new ArgumentException();
  }