七、超時測試

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

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

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

@Timeout 註解樣例

TimeoutTest.Java test class for timeout test.

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. package in.co.javatutorials;  
  2.    
  3. import org.junit.Test;  
  4.    
  5. /** 
  6. * @author javatutorials.co.in 
  7. */  
  8. public class TimeoutTest {  
  9.    
  10.     /** 
  11.      * Example of timeout test. 
  12.      * Test will fail if it takes more than 200 ms to execute 
  13.      */  
  14.     @Test(timeout = 200)  
  15.     public void testTimeout() {  
  16.         while (true);  
  17.     }  
  18. }  

樣例輸出結果

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


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

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

Timeout 規則

TimeoutRuleTest.java 測試Timeout 規則的測試類:
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. package in.co.javatutorials;  
  2.    
  3. import org.junit.Rule;  
  4. import org.junit.Test;  
  5. import org.junit.rules.Timeout;  
  6.    
  7. /** 
  8. * @author javatutorials.co.in 
  9. */  
  10. public class TimeoutRuleTest {  
  11.    
  12.     /** 
  13.      *  Rule is applied to all methods of class 
  14.      *  time is specified in milliseconds 
  15.      */  
  16.     @Rule  
  17.     public Timeout timeout = new Timeout(1000);  
  18.    
  19.     /** 
  20.      * Example of timeout test. 
  21.      * Test will fail if it takes more than 1 sec to execute 
  22.      */  
  23.     @Test  
  24.     public void testTimeout1() {  
  25.         while(true);  
  26.     }  
  27.    
  28.     /** 
  29.      * Example of timeout test. 
  30.      * Test will fail if it takes more than 1 sec to execute 
  31.      */  
  32.     @Test  
  33.     public void testTimeout2() {  
  34.         while(true);  
  35.     }      
  36. }  

樣例結果輸出

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

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