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

2

23

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?

Yalta answered 10/11, 2014 at 15:33 Comment(2)
possible duplicate of Understanding try catch finally with returnGauntlett
Sorry, I understand the classic try, catch and finally flow. This question is different in the sense its related Junit test flow.Yalta
A
26

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.

Almeria answered 10/11, 2014 at 15:37 Comment(0)
I
3

Yes. Finally blocks are meant to be a container for code that fire no matter what. JUnit, or this example, is no different.

Inconsistent answered 10/11, 2014 at 15:47 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.