Finally, in Java Junit 4

In my tests, I use a database connection, I open a connection in @Before and close it in @After .

My question is: what happens if an exception was thrown during the test?

How can I close the connection?

I am looking for something that is equivalent to finally that appears after a try and catch block.

+4
source share
1 answer

@After will do what you want. According to the documentation :

All @After methods are guaranteed to execute, even if the Before or Test method throws an exception.

(This intuitively makes sense to me, since I imagine that the test method is completed in a try block that will catch any exception and convert it to a test failure. Therefore, the test fails, then the break block is executed).

Note that it does not indicate that the method will be started if Error is reset. Usually, if you only use the @After method to maintain the state of the test, and this does not present a problem, because in this case there will be no tests. If you use any resources in the test that absolutely must be cleaned up (for example, your own interceptors), then it is best to do this in the try-finally block in the test method itself.

+6
source

All Articles