[英]How to throw `InterruptedException` while junit testing my class?
[英]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,从而导致测试完成。
但是第二个测试(infiniteLoop)呢? 它没有抛出任何东西。 超时后如何停止?
超时规则在单独的线程中运行每个测试,并等待超时。 超时后,线程被中断。 然后,测试跑步者将继续进行下一个测试。 它不等待对中断的任何响应,因此测试可以自由地在后台继续运行。
infiniteLoop
不会抛出任何InterruptedException
而是在运行所有其余测试的同时继续运行。
一旦所有测试完成,运行测试的JVM通常就会终止,其中的所有线程也会终止。 因为这些线程被标记为守护程序线程,或者通过System.exit
调用。
查看源代码:
System.exit
Eclipse测试运行程序。 在两个测试中都应该抛出该异常,@Rule批注将计时器附加到每个测试中。 如果测试运行超过20毫秒,则会引发异常。 因此,在您的程序中,第二个测试也应触发InterruptedException。
我尝试了以下代码,并且它正常运行(即,由于超时20ms,两个测试均失败)我正在使用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) {
}
}
}
请注意,我在类声明中删除了static
修饰符(据我所知,对于类而言是不允许的),并且更改了Timeout
声明(当前不推荐使用)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.