Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the 'finally' block fire even after a Junit test throws an Assertion Error from with in 'try' block?

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?

like image 400
Hari Krishna Ganji Avatar asked Nov 10 '14 15:11

Hari Krishna Ganji


People also ask

What happens when JUnit assertion fails?

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.

What happens if exception occurs in finally block java?

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.

What is assertion error in JUnit?

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.

Can we throw exception in finally block in java?

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.


1 Answers

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.

like image 67
dkatzel Avatar answered Oct 23 '22 09:10

dkatzel