TestNG超時測試

在本教程中,我們將演示如何在TestNG中執行超時測試。 「超時」表示如果單元測試花費的時間超過指定的毫秒數,那麼TestNG將會中止它並將其標記爲失敗。

「超時」也可用於性能測試,以確保方法在合理的時間內返回。

創建一個名稱爲:TimeoutTest 的 Maven 項目,其結構如下所示 -

TestNG超時測試

創建一個測試類:TestTimeout.java,其代碼如下 -

package com.yiibai;

import org.testng.annotations.Test;

public class TestTimeout {

    @Test(timeOut = 5000) // time in mulliseconds
    public void testThisShouldPass() throws InterruptedException {
        Thread.sleep(4000);
    }

    @Test(timeOut = 1000)
    public void testThisShouldFail() {
        while (true){
            // do nothing
        }

    }

}

執行上面代碼,得到以下結果 -

[TestNG] Running:
  C:\Users\Administrator\AppData\Local\Temp\testng-eclipse--1892041198\testng-customsuite.xml

PASSED: testThisShouldPass
FAILED: testThisShouldFail
org.testng.internal.thread.ThreadTimeoutException: Method org.testng.internal.TestNGMethod.testThisShouldFail() didn't finish within the time-out 1000
    at com.yiibai.TestTimeout.testThisShouldFail(TestTimeout.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.InvokeMethodRunnable.runOne(InvokeMethodRunnable.java:46)
    at org.testng.internal.InvokeMethodRunnable.run(InvokeMethodRunnable.java:37)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)


===============================================
    Default test
    Tests run: 2, Failures: 1, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 2, Failures: 1, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.XMLReporter@1b40d5f0: 12 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@6ea6d14e: 38 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@4563e9ab: 8 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 15 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@2aaf7cc2: 57 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@45c8e616: 4 ms