Reputation: 2046
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?
Upvotes: 5
Views: 5821
Reputation: 15608
If you want TestNG to continue even if you have tests that lock up, you could put a time out on these tests so TestNG kills them after a certain period of time. After this, you After* methods should be called as usual:
@Test(timeOut = 10000) // 10 seconds
public void f() {...}
Upvotes: 2
Reputation: 424983
The answer is to create a shutdown hook via Runtime
's addShutdownHook
method, like this:
static volatile boolean cleanedUp = false;
static final Object lock = new Object();
@BeforeClass
public static void setup() {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
MyTestClass.tearDown();
}
}
}
@AfterClass
public static void tearDown() {
synchronized (lock) {
if (cleanedUp) return;
// do clean up
cleanedUp = true;
}
}
Using the synchronization ensures the clean up is only executed once.
Upvotes: 4