0

I am writing a JUnit test case for a DSL, and I need to ensure that the method under test does never end (as in this question).

The provided solution is fine, but I would like to use the "new" Executor interface (Java 5.0 onwards):

@Test
public void methodDoesNotReturnFor5Seconds() throws Exception {
  Thread t = new Thread(new Runnable() {
    public void run() {
      methodUnderTest();
    }
  });
  t.start();
  t.join(5000);
  assertTrue(t.isAlive());
  // possibly do something to shut down methodUnderTest
}

How can I translate the above code from the "old" Thread/Runnable interface to the "new" ExecutorService/Executor interface?

Community
  • 1
  • 1
Danilo Piazzalunga
  • 7,590
  • 5
  • 49
  • 75

1 Answers1

1
Future<?> future = Executors.newSingleThreadExecutor().submit(new Runnable() {
    public void run() {
        methodUnderTest();
    } 
});
try {
    future.get(5, TimeUnit.SECONDS);
    fail("The task has completed before 5 seconds");
}
catch (TimeoutException e) {
    // expected
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255