1

私はテストを持っています:

@test(timeout = 50000)

タイムアウトのためにテストが失敗した場合にのみ、いくつかの操作を実行したいと思います。

私は次を試します:

@Test(timeout=60000)
    public void test1() {
    try{
              // code
    }
    catch(Exception e){
        //operations after time out
    }
    }

しかし、うまくいきません。何か助けはありますか?

4

1 に答える 1

1

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();
}
于 2013-01-12T17:08:42.880 に答える