Thread Police for your Unit Tests
October 10th, 2008Writing the new ant I stumbled across the problem of test cases leaving threads behind, after returning control to the runner. My trusted colleague and JUnit Runner expert Mark Burnett and I, knocked up a quick and dirty junit runner that actually allows you to spot such a condition.
Consider the following testcode:
@Test
public void losingThreads() throws InterruptedException {
Thread newThread = new Thread() {
public void run() {
for(;;);
}
};
newThread.start();
}
This thing happily spawns a thread and then returns. You get a green test case, but your IDE might behave somewhat funny as there are still threads open. To help diagnose these problems we came up with this threadpolicerunner.
If you now annotate your test case like this, to use it:
@RunWith(ThreadPoliceRunner.class)
public class ThreadTest {
@Test
public void losingThreads() throws InterruptedException {
Thread newThread = new Thread() {
public void run() {
for(;;);
}
};
newThread.start();
}
@Test
public void notLosingThreads() throws InterruptedException {
Thread newThread = new Thread() {
public void run() {
}
};
newThread.start();
newThread.join();
}
}
Your runner will give you the following feedback:
Nice, isn’t?








