假设我有以下测试:
@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/