views:

28

answers:

3

whas the actual use of 'fail' in junit test case?

A: 

I think the usual use case is to call it when no exception was thrown in a negative test.

Something like the following pseudo-code:

test_addNilThrowsNullPointerException()
{
    try {
        foo.add(NIL);                      // we expect a NullPointerException here
        fail("No NullPointerException");   // cause the test to fail if we reach this            
     } catch (NullNullPointerException e) {
        // OK got the expected exception
    }
}
philippe
+1  A: 

Some cases where I have found it useful:

  • mark a test that is incomplete, so it fails and warns you until you can finish it
  • making sure an exception is thrown:
try{
  // do stuff...
  fail("Exception not thrown");
}catch(Exception e){
  assertTrue(e.hasSomeFlag());
}

For the second case you can use an annotation since JUnit4 (annotation @Test(expected=IndexOutOfBoundsException.class)), but if you also want to inspect the exception, this won't work.

sleske
A: 

lets say you are writing a test case for a -ve flow where the code being tested should raise an exception

try{
   bizMethod(badData);
   fail(); // FAIL when no exception is thrown
} catch (BizException e) {
   assert(e.errorCode == THE_ERROR_CODE_U_R_LOOKING_FOR)
}
kartheek