Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 捕获超时异常_Java_Junit - Fatal编程技术网

Java 捕获超时异常

Java 捕获超时异常,java,junit,Java,Junit,当TC超时时,我如何捕获超时?例如,在下面的TC中,我认为catch块将在超时后执行,但它没有。我希望在超时后执行相同的处理,就像TC因异常而失败一样 @Rule public Timeout globalTimeout = new Timeout(3600000); @Test public void tc1 throws Exception { try { //do stuff } catch (Throwable t) {

当TC超时时,我如何捕获超时?例如,在下面的TC中,我认为catch块将在超时后执行,但它没有。我希望在超时后执行相同的处理,就像TC因异常而失败一样

@Rule 
public Timeout globalTimeout = new Timeout(3600000);

@Test   
public void tc1 throws Exception {  
try {
             //do stuff      
} 
catch (Throwable t) {           
// take screenshot, output results   
}   
}

您还可以尝试通过以下方式测试异常:

@Test(expected=TimeoutException.class)
public void tc1{  
 // call your method with parameter so that it will throws a timeoutexception
}

这意味着,如果该方法抛出TimeoutException,那么测试将正常。

如文档所述:

每个测试都在一个新线程中运行。如果指定的超时时间已过 在测试完成之前,它的执行会通过
Thread.interrupt()
。这在可中断I/O和锁中发生,并且 对象和线程抛出中的方法
InterruptedException

这意味着超时时会抛出
InterruptedException
。识别可丢弃的
类型并处理日志记录案例,如下所示:

@Test   
public void tc1 throws Exception {  
    try {
        //do stuff      
    } 
    catch (Throwable t) {           
        // take screenshot, output results
        if(t instanceof InterruptedException){
            // InterruptedException logging case
        }   
    }   
}

您可以创建第二条规则并将其与超时链接。用于此

@Rule
public final TestRule timeout = RuleChain
    .outerRule(new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description description) {
          if (e instanceof TestTimedOutException)
            ;//do your stuff here.
        }
      })
    .around(new Timeout(3600000));

您不能将处理放在finally块中吗?当超时时,我的catch块似乎不会执行。也不是最后一个街区。@After方法被执行,但我不确定这里是否有易于检查的异常/超时。这个答案对JUnit超时特性的假设是错误的。有关详细信息,请参阅。如果TC通过、失败或超时,则执行此规则-如何将其限制为仅超时?我更改了示例。请看一看。