Skip to content

Latest commit

 

History

History
115 lines (80 loc) · 3.67 KB

199.md

File metadata and controls

115 lines (80 loc) · 3.67 KB

TestNG – 超时测试教程

原文: https://howtodoinjava.com/testng/testng-timeout-test-tutorial/

在运行测试时,某些情况下可能会卡住某些测试,或者可能花费比预期更长的时间。 在这种情况下,您可能需要将所述测试用例标记为失败,然后继续。 在本教程中,我们将学习将 TestNG 测试配置为在某些配置的持续时间后超时

TestNG 允许用户设置时间段,以等待测试完全执行。 超时可以通过两种方式配置:

  • 在套件级别:这将适用于上述 TestNG 测试套件中的所有测试
  • 在每个测试方法级别:这将适用于所述测试方法,并且如果在套件级别配置,则将覆盖时间段

要指定超时持续时间,请使用@Test注解的“timeOut”属性。

@Test ( timeOut = 500 )

让我们创建一个示例测试,并了解 TimeNG 在 TestNG 中的工作原理。

套件级别的超时测试示例

在下面的测试中,我们有两种测试方法,即timeTestOne()timeTestTwo()timeTestOne()将需要 1000 毫秒才能完全执行,而timeTestTwo()将需要 400 毫秒才能完全执行。 我们已经使用Thread.sleep()方法来强制执行时间。

public class TimeoutSuite 
{
	@Test
	public void timeTestOne() throws InterruptedException {
		Thread.sleep(1000);
		System.out.println("Time test method one");
	}

	@Test
	public void timeTestTwo() throws InterruptedException {
		Thread.sleep(400);
		System.out.println("Time test method two");
	}
}

现在将testng.xml文件添加到项目根目录,并将以下代码放入其中。 该代码将超时时间定义为 500ms。

<suite name="Time test Suite" time-out="500" verbose="1" >
  <test name="Timeout Test" >
    <classes>
      <class name="com.howtodoinjava.test.TimeoutSuite" />
    </classes>
  </test>
</suite>

现在使用testng.xml运行以上测试。 以上测试运行的输出如下:

[TestNG] Running: C:\somepath\TestNGExamples\testng.xml

Time test method two

===============================================
Time test Suite
Total tests run: 2, Failures: 1, Skips: 0
===============================================

从测试结果中可以看出,只有timeTestTwo()被执行,因为它的执行时间少于testng.xml文件中定义的超时时间。 timeTestOne()执行被取消,因为完成所需的时间超过配置的超时时间。

现在开始学习在测试方法级别设置超时的方法。

方法级别的超时测试示例

如前所述,您也可以在方法级别指定超时。 这将使您可以灵活地给每个单独的测试方法特定的运行时间。

public class TimeoutMethod 
{
	@Test(timeOut = 500)
	public void timeTestOne() throws InterruptedException {
		Thread.sleep(1000);
		System.out.println("Time test method one");
	}

	@Test(timeOut = 500)
	public void timeTestTwo() throws InterruptedException {
		Thread.sleep(400);
		System.out.println("Time test method two");
	}
}

以上测试运行的输出如下:

[[TestNG] Running: C:\Users\somepath\testng-customsuite.xml

Time test method two
PASSED: timeTestTwo
FAILED: timeTestOne

org.testng.internal.thread.ThreadTimeoutException: Method org.testng.internal.TestNGMethod.timeTestOne() didn't finish within the time-out 500

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

在上述测试方法中,timeTestOne()失败,因为它未在指定的超时时间内完全执行。

祝您学习愉快!