timeout
タイムアウト後に操作を処理するためのコールバックが提供されないため、JUnit のパラメーターを使用してここで説明したことを実行することはできません。
ただし、それを行うための独自のテスト ハーネスを作成することはできます。以下の例では、コードを 1 秒以内に実行したいのですが、実際のコードの実行には 2 秒かかります。この場合、 をキャッチし、TimeoutException
その catch ブロック内で追加の操作を実行できます。
@Test
public void testMe() {
// test must finish within one second
int expectedExecutionInSeconds = 1;
RunnableFuture<String> runnableFuture = new FutureTask<String>(new Callable<String>() {
public String call() throws Exception {
// your actual code goes in here
Thread.sleep(2000);
return "ok";
}
});
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(runnableFuture);
try {
String result = runnableFuture.get(expectedExecutionInSeconds, TimeUnit.SECONDS);
assertEquals("ok", result);
}
catch (TimeoutException ex) {
// stop code
runnableFuture.cancel(true);
System.out.println("do other stuff");
}
catch (Exception e) {
fail("other stuff is failing");
}
executorService.shutdown();
}