The fail() method belongs to JUnit 4 org. junit. Assert class. The fail assertion fails a test throwing an AssertionError. It can be used to verify that an actual exception is thrown or when we want to make a test failing during its development.
The Assert. Fail method provides you with the ability to generate a failure based on tests that are not encapsulated by the other methods.
Conclusion. Both failure and error in JUnit tests indicate an undesired situation, but their semantics are different. Failures notify of an invalid test result, errors indicate an unexpected test execution.
In case of Test3, the tester is purposely trying to cause the test case to fail in order to showcase how to run failed test cases. Therefore, the code includes @Asert. assertTrue(false); to fail this particular test case. Save all these test cases.
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()
.
Let's say you are writing a test case for a negative 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)
}
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
}
}
I've used it in the case where something may have gone awry in my @Before method.
public Object obj;
@Before
public void setUp() {
// Do some set up
obj = new Object();
}
@Test
public void testObjectManipulation() {
if(obj == null) {
fail("obj should not be null");
}
// Do some other valuable testing
}
This is how I use the Fail method.
There are three states that your test case can end up in
intended (Unlike negative test cases that expect a exception to occur).
If you are using eclipse there three states are indicated by a Green, Blue and red marker respectively.
I use the fail operation for the the third scenario.
e.g. : public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With