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

末鹿安然 提交于 2019-12-06 17:49:59

问题


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?


回答1:


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 Exception if you wanted)




回答2:


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



来源:https://stackoverflow.com/questions/26847237/will-the-finally-block-fire-even-after-a-junit-test-throws-an-assertion-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!