在測試類的方法上使用 @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 窗口中顯示如下: