In my tests I’m using a connection to a DB, I open the connection in @Before
and close it in @After.
My question is what happens if an exception was thrown during the test?
How would I be able to close the connection?
I’m looking for something that is equivalent to finally that comes after try and catch block.
@Afterwill do what you want. According to its documentation:(This intuitively makes sense to me, since I imagine the test method as wrapped in a
tryblock that will catch any exception and convert it to a test failure. Hence the test fails, then the teardown block runs.)Note that it doesn’t specify that the method will run if an
Erroris thrown. Usually though you’d only use the@Aftermethod to maintain the test state, and this won’t present a problem because no more tests would run anyway in this case. If you do use any resources in the test that absolutely have to be cleaned up (e.g. native hooks), then it’s best to do this in atry-finallyblock within the test method itself.