java - 捕获超时异常

标签 java junit

当 TC 超时时,我如何捕获超时?例如,在下面的 TC 中,我认为 catch block 会在超时后执行,但事实并非如此。我想在超时后进行相同的处理,就好像 TC 异常失败一样。

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

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

最佳答案

正如文档所说:

Each test is run in a new thread. If the specified timeout elapses before the test completes, its execution is interrupted via Thread.interrupt(). This happens in interruptable I/O and locks, and methods in Object and Thread throwing InterruptedException.

这意味着 InterruptedException 在超时时被抛出。识别 Throwable 类型并处理日志记录情况,如下所示:

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

关于java - 捕获超时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30212543/

相关文章:

java - 如何将网站的 HTML 转换为图像?

java - 使用junit启动和控制spring应用程序

java - NoClassDefFoundError:注释处理期间的 org/junit/AfterClass

java - junit 在 win32 下测试具有 shell 脚本功能的类

java - 如何从命令行执行 Junit 测试用例

java - 更改 Servlet 发布位置?

java - 如何为 csv java 记录器文件设置 header 。使用记录器 java.util.logging.Logger

java - JDialog - 如何使回车键响应按钮焦点在对话框上

java - 在 <applet> 标记中指定属性

java - Mockito 的 JUnit 模拟环境不起作用,评估结果仍然为 null