Junit 4 Tutorials(Junit 4 教程) Junit4 七、超時測試

Junit 4超時測試(Timeout test)可以被用來測試方法的執行時間。 Junit 4 超時測試可以被用在:
  • 在測試類的方法上使用 @Timeout 註解
  • 測試類的所有方法應用 Timeout規則

在測試類的方法上使用 @Timeout 註解

Junit 4 提供了 @Timeout 註解來測試任意特定方法的執行時間。如果測試方法的執行時間大於指定的超時參數,測試方法將拋出異常,測試結果爲失敗。指定的超時參數是以毫秒記.

@Timeout 註解樣例

TimeoutTest.java test class for timeout test.

package in.co.javatutorials;
 
import org.junit.Test;
 
/**
* @author javatutorials.co.in
*/
public class TimeoutTest {
 
    /**
     * Example of timeout test.
     * Test will fail if it takes more than 200 ms to execute
     */
    @Test(timeout = 200)
    public void testTimeout() {
        while (true);
    }
}

樣例輸出結果

結果在 eclipse junit 窗口中顯示如下:


測試類的所有方法應用 Timeout規則

Junit 4 提供了 Timeout 規則來測試類中的所有方法。如果類中的任意一個方法執行時間超過了在Timeout 規則中規定的值,測試方法將拋出異常,測試結果爲失敗。指定的超時參數是以毫秒記。

Timeout 規則

TimeoutRuleTest.java 測試Timeout 規則的測試類:
package in.co.javatutorials;
 
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
 
/**
* @author javatutorials.co.in
*/
public class TimeoutRuleTest {
 
    /**
     *  Rule is applied to all methods of class
     *  time is specified in milliseconds
     */
    @Rule
    public Timeout timeout = new Timeout(1000);
 
    /**
     * Example of timeout test.
     * Test will fail if it takes more than 1 sec to execute
     */
    @Test
    public void testTimeout1() {
        while(true);
    }
 
    /**
     * Example of timeout test.
     * Test will fail if it takes more than 1 sec to execute
     */
    @Test
    public void testTimeout2() {
        while(true);
    }    
}

樣例結果輸出

結果在 eclipse junit 窗口中顯示如下:



源碼下載

點擊我下載源碼

教程目錄導航



---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

本文出處爲 http://blog.csdn.net/luanlouis,轉載請註明出處,謝謝!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章