Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junit4 - Cleanup on test timeout

When I run a test with annotation @Test(timeout = 3000) and it times out, it kills the test immediately and does not call my tearDown method annotated with @After.

What would be the way to clean up in such a scenario?

EDIT: My test is invoking resource end points using jax-rs over the wire and the test times out in the middle of a http request. This is the case I am fairly certain that @After is not being invoked

like image 998
Prasanna Avatar asked Feb 24 '11 08:02

Prasanna


2 Answers

Strictly speaking, it doesn't kill the test, it fails it. Which apparently means that the method annotated with @After will run.

The code below is working like charm for me.

@Test(timeout=1)
public void testTimeout() {
    try {
        Thread.sleep(10);
    } catch (InterruptedException ex) {}
}

@After
public void after() {
    System.out.println("@After is invoked, indeed.");
}

Output is,

Testsuite: javaapplication1.MainTest
After is invoked, indeed.
Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0.054 sec
like image 159
Adeel Ansari Avatar answered Oct 05 '22 10:10

Adeel Ansari


I had some problems with the timeout attribute, too. Maybe this helps you in finding four problem...

In my case the confusion was caused by the fact that the test code in a method annotated with @Test(timeout=...) is run in a separate thread. Therefore some ThreadLocal stuff I accessed during the test could not be cleaned up in the @After method.

like image 45
jens Avatar answered Oct 05 '22 11:10

jens