开发者

In NUnit, how can I explicitly fail a test

For example the code below,

[Test()]
public void Test( )
{
   try{
      Ge开发者_StackOverflow中文版tNumber( );
   }
   catch( Exception ex ){
       /* fail here */
   }

   ...
}

I want to fail my test when GetNumber method throw an exception.

Please advise.

Many thanks.


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


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:

  1. Use Assert.DoesNotThrow - this very explicitly documents intent
  2. As other people have suggested, you can simply opt to not catch the exception. Test failures are already signaled by exceptions. Any uncaught exception will fail a test
  3. If you have a good reason for your logic to explicitly fail or pass a test, and don't have other assertion blocks you could use instead (ones that better document the intent of your test), use Assert.Fail / Assert.Pass

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


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜