Some of my TestNG tests involve persistent data usage. When the test is finished some actions should be performed to restore the state of data (e.g. cleaning up). I solve this using @AfterClass or @AfterMethod.
The problem is that sometimes during the development my test hangs up and I need to terminate it manually. When terminating JVM process running test I have to perform all post-test actions by myself.
Is there any way I can terminate the test so that my @After* methods are invoked?
The answer is to create a shutdown hook via
Runtime‘saddShutdownHookmethod, like this:Using the synchronization ensures the clean up is only executed once.