java - JUnit 中如何处理超时?

标签 java junit

假设我有以下测试:

@Test(timeout = 1)
public void test(){
  while(true){}
}

这模拟了一个需要很长时间才能返回的测试,不是从 sleep 中返回,而是从原始计算时间返回。测试如何退出?如果我创建一个线程并尝试同样的事情,它不会编译。

public static void main(String[] args) {
    Thread thread = new Thread() {
        public void run() {
            try {
                while (true) {
                }
            } catch (InterruptedException e) {//Exception 'java.lang.InterruptedException' is never thrown in the corresponding try block'
                e.printStackTrace();
            }
        }
    };
    thread.start();
    thread.interrupt();
}

我什至可以尝试复制实现,但它仍然不会中断线程:

public static void main(String[] args) {
    Thread thread = new Thread() {
        public void run() {
            try {
                doTest();
            } catch (InterruptedException throwable) {
                System.out.println("interrupted");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        private void doTest() throws Throwable {
            while (true) {
            }
        }
    };
    thread.start();
    thread.interrupt();
}

java.lang.Exception: test timed out after 1 ms 异常声称源自运行常规测试时的 while 循环。

我对测试如何“中断”感到困惑,但我无法对常规线程执行相同的操作。 JUnit 中如何实现这种“中断”功能?

最佳答案

关于java - JUnit 中如何处理超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080328/

相关文章:

java - 创建连接到 HBaseTestingUtility 的 HBaseAdmin

java - 在测试中再现 SimpleDateFormat 非线程安全

java - 构造函数和关键字 'this'

java - Seam 应用架构

java - CORBA(orbd)联网配置?

eclipse - 如何在每次执行 JUnit 测试之前自动执行脚本?

java - JUnit 测试抛出异常的方法

java - junit 检测测试是否是唯一运行的一个

java - 如何通过命令控制台/终端执行脚本后显示 SVG 图像?

java - Spring 。 "schemaLocation ... must have even number of URI' 秒”