我有一个测试,使用:
@test(timeout = 50000)
我想做一些操作,如果测试失败,因为超时,只有这样。
我试了下一个:
@Test(timeout=60000)
public void test1() {
try{
// code
}
catch(Exception e){
//operations after time out
}
}
但是它不起作用。任何帮助吗?
无法对JUnit的timeout
参数执行此处描述的操作,因为它在超时后不提供回调来处理操作。
但是,您当然可以编写自己的测试工具来做到这一点。在下面的例子中,我希望代码在一秒内执行,但实际的代码执行需要2秒。在这种情况下,我们捕获TimeoutException
,您可以在该捕获块中执行额外的操作。
@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();
}