47

Can someone tell me why this unit test that checks for exceptions fails? Obviously my real test is checking other code but I'm using Int32.Parse to show the issue.

[Test]
public void MyTest()
{
    Assert.That(Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());
}

The test fails, giving this error. Obviously I'm trying to test for this exception and I think I'm missing something in my syntax.

Error   1   TestCase '.MyTest'
failed: System.FormatException : Input string was not in a correct format.
at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at System.Int32.Parse(String s)

based on the documentation at Throws Constraint (NUnit 2.5)

Jason More
  • 6,983
  • 6
  • 43
  • 52

2 Answers2

77

Try this instead:

Assert.That(() => Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>());

Basically you need to pass a delegate to Assert.That, just like the documentation in your link states (note that I've used a lambda expression here, but it should be the same).

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
  • 1
    ah I had to make in an anonymous delegate... I see that in the documentation now, it just wasn't super clear. Thanks! – Jason More Mar 25 '10 at 15:12
  • 3
    Incase someone runs into the fact that their anonymous function returns void, you'll need to do something like: `Assert.That(new Action(() => VoidReturningMethod("abc")), Throws.Exception.TypeOf());` – Marty Neal Feb 01 '13 at 16:59
  • Thanks @MartinNeal that helped me on the right path, but for me it complained that it had to be a TestDelegate, so I had to do: `new TestDelegate(() => AddBlockingTaskToBox())` or – Brondahl Apr 19 '16 at 20:42
9

What test runner are you using? Not all of them work correctly with the exception assertions.

You may have better luck using [ExpectedException (typeof(FormatException))] or even Assert.Throws<FormatException> (() => Int32.Parse("abc"));

ermau
  • 1,303
  • 7
  • 19
  • I was using TDD.net and nUnit gui. Your fix worked, but I want to use the fluent syntax. I gave you a point though for the help! – Jason More Mar 25 '10 at 15:13
  • 1
    I know this is an old answer that was right at that moment. But for now and future reference, `ExpectedException` attribute is deprecated on NUnit 3.0: https://github.com/nunit/docs/wiki/Breaking-Changes – ferpega Nov 08 '16 at 17:04