Java / test&超时后的操作

时间:2013-01-12 15:03:33

标签: java testing

我有一个测试,有:

@test(timeout = 50000)

如果测试因超时而失败,我想做一些操作,然后才开始。

我尝试下一个:

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

但它不起作用。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

使用JUnit的timeout参数执行此处所描述的操作是不可能的,因为它在超时后不提供回调来处理操作。

但是,你当然可以编写自己的测试工具来做到这一点。在下面的示例中,我希望代码在一秒钟内执行,但我的实际代码执行需要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();
}