Legacy Documentation. View NUnit 3 Documentation

Throws Constraint (NUnit 2.5)

ThrowsConstraint is used to test that some code, represented as a delegate, throws a particular exception. It may be used alone, to merely test the type of constraint, or with an additional constraint to be applied to the exception specified as an argument. p>The related ThrowsNothingConstraint simply asserts that the delegate does not throw an exception.

Constructors

ThrowsConstraint(Type expectedType)
ThrowsConstraint<T>()
ThrowsConstraint(Type expectedType, Constraint constraint)
ThrowsConstraint<T>(Constraint constraint)
ThrowsNothingConstraint()

Syntax

Throws.Exception
Throws.TypeOf(Type expectedType)
Throws.TypeOf<T>()
Throws.InstanceOf(Type expectedType)
Throws.InstanceOf<T>()
Throws.Nothing

Examples of Use

// .NET 1.1
Assert.That( new TestDelegate(SomeMethod),
  Throws.TypeOf(typeof(ArgumentException)));
Assert.That( new TestDelegate(SomeMethod),
  Throws.Exception.TypeOf(typeof(ArgumentException)));
Assert.That( new TestDelegate(SomeMethod),
  Throws.TypeOf(typeof(ArgumentException))
    .With.Property("Parameter").EqualTo("myParam"));

// .NET 2.0
Assert.That( SomeMethod,
  Throws.TypeOf<ArgumentException>());
Assert.That( SomeMethod,
  Throws.Exception.TypeOf<ArgumentException>());
Assert.That( SomeMethod,
  Throws.TypeOf<ArgumentException>()
    .With.Property("Parameter").EqualTo("myParam"));

Notes

  1. Throws.Exception may be followed by further constraints, which are applied to the exception itself as shown in the last two examples above. It may also be used alone to verify that some exception has been thrown, without regard to type. This is not a recommended practice since you should normally know what exception you are expecting.
  2. Throws.TypeOf and Throws.InstanceOf are provided as a shorter syntax for this common test. They work exactly like the corresponding forms following Throws.Exception.