TestNG timeOut example(java單元測試@Test timeOut)
阿新 • • 發佈:2019-02-10
【本系列其他教程正在陸續翻譯中,點選分類:TestNG進行檢視。】
【翻譯 by 明明如月 QQ 605283073】
本文介紹TestNG測試的 超時。
可以通過@Test(timeOut = 1000) 註解來實現TestNG
超時特性。
如果一個帶有@Test註解的測試方法應該在很短時間內執行完畢但是卻執行了很長時間,我們就應該去研究研究。
@Test(timeOut
= 1000) 表示此測試方法 應該在1000毫秒(一秒鐘) 沒完成。 如果沒有在此時間內完成,
此測試方法也算失敗。
被測試類:
package com.websystique.testng; public class Calculator { public double add(double a, double b){ return a+b; } public double subtract(double a, double b) throws InterruptedException{ Thread.sleep(5000); return a-b; } }
在 subtract (減法)方法中有 Thread.sleep(5000),讓執行緒訊息5000毫秒。
編寫測試類:
package com.websystique.testng; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestNGTimeOutExample { Calculator calculator; @BeforeClass public void setup() { System.out.println("setup()"); calculator = new Calculator(); } @AfterClass public void tearDown() { System.out.println("tearDown()"); calculator = null; } @BeforeMethod public void beforeMethod() { System.out.println("beforeMethod()"); } @AfterMethod public void afterMethod() { System.out.println("afterMethod()"); } @Test public void testAdd() { System.out.println("testAdd()"); Assert.assertEquals(calculator.add(3, 4), 7.0); } @Test(timeOut = 3000)//timeout in milliseconds public void testSubtract() throws InterruptedException { System.out.println("testSubtract()"); Assert.assertEquals(calculator.subtract(5, 2), 3.0); } }
通過TestNG Eclipse 外掛或者mvn clean test 來執行
測試結果setup() beforeMethod() testAdd() afterMethod() beforeMethod() testSubtract() afterMethod() tearDown() PASSED: testAdd FAILED: testSubtract org.testng.internal.thread.ThreadTimeoutException: Method org.testng.internal.TestNGMethod.testSubtract() didn't finish within the time-out 3000 at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.doSignalAll(AbstractQueuedSynchronizer.java:1890) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.signalAll(AbstractQueuedSynchronizer.java:1959) at java.util.concurrent.ThreadPoolExecutor.tryTerminate(ThreadPoolExecutor.java:707) at java.util.concurrent.ThreadPoolExecutor.processWorkerExit(ThreadPoolExecutor.java:1006) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1163) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) =============================================== Default test Tests run: 2, Failures: 1, Skips: 0 ===============================================
可以看出 此測試方法 執行超過了3秒鐘,因此測試未通過。