【本系列其他教程正在陆续翻译中,点击分类:TestNG进行查看。】
【翻译 by 明明如月 QQ 605283073】
原文:http://websystique.com/java/testing/testng-timeout-example/
本文介绍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秒钟,因此测试未通过。