What\'s the actual use of \'fail\' in JUnit test case?
Some cases where I have found it useful:
try{ // do stuff... fail("Exception not thrown"); }catch(Exception e){ assertTrue(e.hasSomeFlag()); }
Note:
Since JUnit4, there is a more elegant way to test that an exception is being thrown:
Use the annotation @Test(expected=IndexOutOfBoundsException.class)
However, this won't work if you also want to inspect the exception, then you still need fail()
.
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
}
}