简体   繁体   中英

nUnit Assert.That(method,Throws.Exception) not catching exceptions

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)

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).

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM