簡體   English   中英

如果JUnit測試失敗並超時,它將運行finally子句嗎?

[英]If a JUnit test fails with timeout will it run a finally clause?

假設我們有一個帶有超時的junit測試,如下所示:

@Test(timeout=10)
public void testWithTimeout(){
    try{
        doSomethingLongerThan10();
    } finally {
        cleanup();
    }
}

如果測試花費更長的時間並以超時結束,它將運行finally子句嗎? 它會結束嗎? 它將使線程繼續運行嗎?

我在自己的測試中觀察到,finally子句未運行,但我不知道是否在每個可能的jUnit測試中都采用這種方式,還是取決於版本或運行程序類。

編輯:感謝Sotirios Delimanolis指出“不良測試”


因為我很好奇,所以我做了測試:

public class Foo {
    @Test(timeout=10)
    public void testWithTimeout() {
        try {
            while(true)
                ;
        } finally {
            System.out.println("did run");
        }
    }
}

輸出:

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)

所以答案是否定的。 (junit 4.12)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM