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

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

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

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

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

  1. @Test ( timeOut = 500 )

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

套件级别的超时测试示例

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

  1. public class TimeoutSuite
  2. {
  3. @Test
  4. public void timeTestOne() throws InterruptedException {
  5. Thread.sleep(1000);
  6. System.out.println("Time test method one");
  7. }
  8. @Test
  9. public void timeTestTwo() throws InterruptedException {
  10. Thread.sleep(400);
  11. System.out.println("Time test method two");
  12. }
  13. }

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

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

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

  1. [TestNG] Running: C:\somepath\TestNGExamples\testng.xml
  2. Time test method two
  3. ===============================================
  4. Time test Suite
  5. Total tests run: 2, Failures: 1, Skips: 0
  6. ===============================================

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

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

方法级别的超时测试示例

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

  1. public class TimeoutMethod
  2. {
  3. @Test(timeOut = 500)
  4. public void timeTestOne() throws InterruptedException {
  5. Thread.sleep(1000);
  6. System.out.println("Time test method one");
  7. }
  8. @Test(timeOut = 500)
  9. public void timeTestTwo() throws InterruptedException {
  10. Thread.sleep(400);
  11. System.out.println("Time test method two");
  12. }
  13. }

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

  1. [[TestNG] Running: C:\Users\somepath\testng-customsuite.xml
  2. Time test method two
  3. PASSED: timeTestTwo
  4. FAILED: timeTestOne
  5. org.testng.internal.thread.ThreadTimeoutException: Method org.testng.internal.TestNGMethod.timeTestOne() didn't finish within the time-out 500
  6. ===============================================
  7. Default test
  8. Tests run: 2, Failures: 1, Skips: 0
  9. ===============================================

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

祝您学习愉快!