Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 869
Jason More Avatar asked Mar 25 '10 15:03

Jason More


People also ask

How do I assert exceptions in NUnit?

It's also in a class by itself in that it returns an Exception, rather than void, if the Assert is successful. See the example below for a few ways to use this. Assert. Throws may be used with a constraint argument, which is applied to the actual exception thrown, or with the Type of exception expected.

How do you assert if an exception is thrown?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

What assert throws?

Assert. Throws returns the exception that's thrown which lets you assert on the exception. var ex = Assert.

How do I expect an exception in JUnit 5?

In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.


2 Answers

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

like image 132
Klaus Byskov Pedersen Avatar answered Sep 21 '22 10:09

Klaus Byskov Pedersen


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

like image 37
ermau Avatar answered Sep 19 '22 10:09

ermau