Will the writer.close()
method inside the finally { }
block run on an Junit Assertion Error?
Assume the following code:
@Test
public void testWriter() {
try {
writer.open();
final List<MyBean> myBeans = new ArrayList<ProfileBean>();
/** Add 2 beans to the myBeans List here. **/
final int beansWritten = writer.writeBeans(myBeans);
// Say this assertion error below is triggered
org.junit.Assert.assertEquals("Wrong number of beans written.", -1, profilesWritten);
} finally {
writer.close(); // will this block run?
}
}
Now will the finally()
block run just like a regular flow?
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. In JUnit 5 all JUnit 4 assertion methods are moved to org.
The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.
When JUnit Assertion errors (test failures) occur, your test will stop executing and will not perform any remaining Assertions. For tests containing only a single Assertion, as is often the case, this is not an issue.
Methods invoked from within a finally block can throw an exception. Failure to catch and handle such exceptions results in the abrupt termination of the entire try block.
Yes, the finally
block will run. Junit assertion errors are just normal exceptions so the usual java try-catch-finally
pattern will work. You can even catch the AssertionError
exception if you wanted.
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