Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In NUnit, how can I explicitly fail a test

Tags:

nunit

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.

like image 788
domlao Avatar asked Jul 11 '11 05:07

domlao


People also ask

How do I Assert failed in NUnit?

Assert. Fail(); Assert. Fail(string message, params object[] params); Here's an example of its use to create a private assertion that tests whether a string contains an expected value.

How do you rerun failed test cases in NUnit?

You can add a new attribute in the nunit based on the attribute repeat and rebuild the library. It's very simple. Show activity on this post. Starting with NUnit 3.0, there is a 'Retry' attribute that looks like it will do exactly what kumar wants.

Why are my NUnit tests ignored?

Ignored tests are displayed by the runners as warnings in order to provide a reminder that the test needs to be corrected or otherwise changed and re-instated.


3 Answers

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

like image 186
alexn Avatar answered Oct 21 '22 12:10

alexn


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

like image 45
Merlyn Morgan-Graham Avatar answered Oct 21 '22 11:10

Merlyn Morgan-Graham


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.

like image 1
adt Avatar answered Oct 21 '22 12:10

adt