Is NUnit ExpectedExceptionAttribute the only way to check if something throws an exception?

I am completely new to C # and NUnit.

Boost.Test has a macro family BOOST_*_THROW. There is a method in the Python test module TestCase.assertRaises.

As I understand it, in C # with NUnit (2.4.8), the only method for checking exceptions is to use ExpectedExceptionAttribute.

Why do I prefer ExpectedExceptionAttributeover - let say - Boost.Test approach? What reasoning can be behind this design decision? Why is this better with C # and NUnit?

Finally, if I decide to use it ExpectedExceptionAttribute, how can I do some additional tests after the exception has been raised and caught? Let's say that I want to check the requirement that the object must be valid after any setter has raised System.IndexOutOfRangeException. How would you fix the following code to compile and work as expected?

[Test]
public void TestSetterException()
{
    Sth.SomeClass obj = new SomeClass();

    // Following statement won't compile.
    Assert.Raises( "System.IndexOutOfRangeException",
                   obj.SetValueAt( -1, "foo" ) );

    Assert.IsTrue( obj.IsValid() );
}

Edit: Thanks for your answers. Today I found a blog entry mentioning all three of the methods you described (and another minor variation). I am ashamed that I could not find him before: - (.

+5
source share
5 answers

I am surprised that I have not seen this template yet. David Arnault is very similar, but I prefer the simplicity of this:

try
{
    obj.SetValueAt(-1, "foo");
    Assert.Fail("Expected exception");
}
catch (IndexOutOfRangeException)
{
    // Expected
}
Assert.IsTrue(obj.IsValid());
+13

NUnit 2.5, .

Assert.That( delegate { ... }, Throws.Exception<ArgumentException>())
+10

MbUnit

Assert.Throws<IndexOutOfRangeException>(delegate {
    int[] nums = new int[] { 0, 1, 2 };
    nums[3] = 3;
});
+4

:

bool success = true;
try {
    obj.SetValueAt(-1, "foo");
} catch () {
    success = false;
}

assert.IsFalse(success);

...
+2

:

Assert.Raises( "System.IndexOutOfRangeException",
               obj.SetValueAt( -1, "foo" ) );

woiuldn't # - obj.SetValueAt , Assert.Raises. SetValue , Assert.Raises.

:

void Raises<T>(Action action) where T:Exception {
   try {
      action();
      throw new ExpectedException(typeof(T));
   catch (Exception ex) {
      if (ex.GetType() != typeof(T)) {
         throw;
      }
   }
}

:

Assert.Raises<System.IndexOutOfRangeException>(() => 
  obj.SetValueAt(-1, "foo")
;
+2

All Articles