Reputation: 16029
For example the code below,
[Test()]
public void Test( )
{
try{
GetNumber( );
}
catch( Exception ex ){
/* fail here */
}
...
}
I want to fail my test when GetNumber method throw an exception.
Please advise.
Many thanks.
Upvotes: 11
Views: 13731
Reputation: 1484
[Test()]
public void Test( )
{
GetNumber();
}
Failing a test is equivalent to throwing an exception from it. Therefore, iff your method throws the test will fail.
Upvotes: 0
Reputation: 59111
If GetNumber()
returns a value, you shouldn't do what you're trying to do. Instead, you should assert the return value. Don't bother checking for exceptions if you don't expect one to arise. The NUnit framework will take care of that and fail your test for you.
If GetNumber()
doesn't return a value, you can do one of three things:
In this case, the first option is the most explicit. This is common if the only interesting side-effect you can validate is if an exception gets thrown. But if GetNumber()
doesn't return a value, you should really consider renaming your method :)
Upvotes: 4
Reputation: 58982
You don't need to wrap GetNumber() inside a try/catch. If GetNumber() throws, your test will fail.
If you need to fail it explicitly, use Assert.Fail();
Upvotes: 31
Reputation: 10662
Assert.Fail()
: http://www.nunit.org/index.php?p=utilityAsserts&r=2.2.7
Although, there is probably an assertion to Assert.NoThrow, or something like that, that ensures your method doesn't throw.
Upvotes: 1
Reputation: 4360
All test should pass, if you are expecting an exception you should use ExpectedException attribute. If your code throws the expected exception test will pass.
Upvotes: 1