假设我们有一个带有超时的 junit 测试,如下所示:
@Test(timeout=10)
public void testWithTimeout(){
try{
doSomethingLongerThan10();
} finally {
cleanup();
}
}
Run Code Online (Sandbox Code Playgroud)
如果测试需要更长的时间并以超时结束,它会运行 finally 子句吗?它会结束吗?它会让线程运行吗?
我在自己的测试中观察到 finally 子句没有运行,但我不知道在每个可能的 jUnit 测试中是否都是这种方式,或者它取决于版本或运行程序类。
小智 5
编辑:感谢 Sotirios Delimanolis 指出“糟糕的测试”
因为我很好奇我确实测试了它:
public class Foo {
@Test(timeout=10)
public void testWithTimeout() {
try {
while(true)
;
} finally {
System.out.println("did run");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
org.junit.runners.model.TestTimedOutException: test timed out after 10 milliseconds
at so32723397.Foo.testWithTimeout(Foo.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:298)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.lang.Thread.run(Thread.java:745)
Run Code Online (Sandbox Code Playgroud)
所以答案是否定的。(4.12 节)