如何保持 TestNG.xml 中指定的执行顺序?

testngrest assureddynamic programming更新于 2025/5/6 5:37:17

在最新版本中,TestNG 按照 TestNG.xml 或任何可执行 XML 文件中指定的顺序执行类。但是,在旧版本中运行 tesng.xml 时,有时无法按顺序执行。TestNG 可能会以随机顺序运行类。在最新版本中,TestNG 按照 TestNG.xml 或任何可执行 XML 文件中指定的顺序执行类。但是,在旧版本中运行 tesng.xml 时,有时无法按顺序执行。TestNG 可能会以随机顺序运行类。

在本文中,我们将讨论如何确保执行顺序保持 tesng.xml 中的顺序。

TestNG 支持两个属性 - parallel 和 reserve-order。这些属性在 tests.xml 中使用。

  • Parallel 属性用于并行运行测试。因此,首先要检查执行是否并行进行,以保持执行顺序。并行属性在套件级别提及,因此请添加 parallel = "none" 而不是 parallel="。

  • Preserver-order 属性在测试级别使用。TestNG 在旧版 jar 中默认将该值设为 false。这可能会导致随机执行。为了确保执行顺序正确,我们在testing.xml中将属性赋值为true。

现在,我们将了解如何实现这两个属性,以确保根据testing.xml保留执行顺序。

解决此问题的方法/算法

  • 步骤1:创建两个TestNG类:OrderofTestExecutionInTestNG和NewTestngClass

  • 步骤2:在这两个类中分别编写两个不同的@Test方法:OrderofTestExecutionInTestNG和NewTestngClass。

  • 步骤3:现在创建testNG.xml来运行这两个TestNG类,并设置parallel=none和preserve-order=true,如下所示。

  • 步骤4:现在,运行testNG.xml或直接在IDE中运行testNG类,或者编译并运行使用命令行执行。

示例

以下是 TestNG 类的代码 - OrderofTestExecutionInTestNG:

import org.testng.annotations.*;

public class OrderofTestExecutionInTestNG {
    // test case 1
    @Test
    public void testCase1() {
        System.out.println("in test case 1 of OrderofTestExecutionInTestNG");
    }
    // test case 2
    @Test
    public void testCase2() {
        System.out.println("in test case 2 of OrderofTestExecutionInTestNG");
    }
 }   

以下是常见 TestNG 类的代码 - NewTestngClass:

import org.testng.annotations.*;

public class NewTestngClass {

    @Test
    public void testCase1() {
        System.out.println("in test case 1 of NewTestngClass");
    }
    @Test
    public void testCase2() {
        System.out.println("in test case 2 of NewTestngClass");
    }
} 

testng.xml

这是一个用于组织和运行 TestNG 测试用例的配置文件。

当需要执行有限的测试而不是全套测试时,它非常方便。

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1" parallel = "none">
   <test name = "test1" preserve-order = "true">
      <classes>
         <class name = "OrderofTestExecutionInTestNG"/>
    <class name = "NewTestngClass"/>
      </classes>
   </test>
</suite>

输出

in test case 1 of OrderofTestExecutionInTestNG
in test case 2 of OrderofTestExecutionInTestNG
in test case 1 of NewTestngClass
in test case 2 of NewTestngClass

===============================================
Suite1
Total tests run: 4, Passes: 4, Failures: 0, Skips: 0
=============================================== 


相关文章