JUnit 和中断异常

JUnit and InterruptedException

我在 JUnit 文档中找到了以下示例:

public static class HasGlobalLongTimeout {

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

    @Test
    public void run1() throws InterruptedException {
        Thread.sleep(100);
    }

    @Test
    public void infiniteLoop() {
        while (true) {}
    }
}

我知道每当 JUnit 试图中断第一个测试时,它会中断它所在的线程 运行,它会抛出 InterruptedException,导致测试完成。

但是第二个测试(无限循环)呢?它没有扔任何东西。超时后如何停止?

它应该在两个测试中都被抛出,@Rule 注释为每个测试附加了一个计时器。如果测试运行超过 20 毫秒,则会触发异常。所以在你的程序中,第二个测试也应该触发一个 InterruptedException。

超时规则运行s 每次在单独的线程中测试,并等待超时。超时后,线程被中断。然后测试 运行ner 将继续进行下一个测试。它不等待对中断的任何响应,因此测试可以在后台自由地继续 运行ning。

infiniteLoop 不会抛出任何 InterruptedException 但会继续 运行ning 而所有剩余的测试都是 运行.

一旦所有测试都完成,然后 JVM 运行通常会终止测试,连同其中的所有线程。要么是因为线程被标记为守护线程,要么是通过 System.exit 调用。

查看源码:

我尝试了以下代码并且它工作正常(即由于 20 毫秒的超时,两个测试都失败了)我正在使用 Java 8 和 JUnit 4.12。

import java.util.concurrent.TimeUnit;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

public class HasGlobalLongTimeout {

    @Rule
    public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);

    @Test
    public void run1() throws InterruptedException {
        Thread.sleep(100);
    }

    @Test
    public void infiniteLoop() {
        while (true) {
        }
    }
}

请注意,我删除了 class 声明中的 static 修饰符(据我所知,classes 不允许这样做)并且我更改了 Timeout 声明(目前已弃用)。