分组测试是 TestNG 中一个新的创新特性,在 JUnit 框架中是没有的。它允许您将方法分派到适当的部分并执行复杂的测试方法分组。
您不仅可以声明属于组的那些方法,还可以指定包含其他组的组。然后,可以调用 TestNG 并要求它包含一组特定的组(或正则表达式),同时排除其他组。
组测试在如何划分测试方面提供了最大的灵活性。如果您想背靠背运行两组不同的测试,则无需重新编译任何内容。
使用<groups>标记在您的testng.xml文件中指定组。它可以在<test>或<suite>标记下找到。<suite>标记中指定的组适用于下面的所有<test>标记。
现在,让我们举个例子来看看小组测试是如何工作的。
解决此问题的方法/算法 -
第 1 步- 创建两个 TestNG 类 - NewTestngClass和OrderofTestExecutionInTestNG。
第 2 步- 在两个类中编写两个不同的@Test方法:NewTestngClass和OrderofTestExecutionInTestNG。
第 3 步- 在代码文件中使用下面提到的组标记每个 @Test。
第 4 步- 现在创建testNG.xml,如下所示执行@Test那些组名为functest。
第 5 步- 运行testNG.xml或直接在 IDE 中运行 testNG 类,或使用命令行编译并运行它。
第 6 步- 根据给定的配置,它将执行 NewTestngClass 的测试用例 1和OrderofTestExecutionInTestNG类的测试用例。
示例
以下代码显示了如何运行测试组 -
src/NewTestngClass.java
import org.testng.annotations.Test; public class NewTestngClass { @Test(groups = { "functest", "checkintest" }) public void testCase1() { System.out.println("in test case 1 of NewTestngClass"); } @Test(groups = {"checkintest" }) public void testCase2() { System.out.println("in test case 2 of NewTestngClass"); } }
src/OrderofTestExecutionInTestNG.java -
import org.testng.annotations.Test; public class OrderofTestExecutionInTestNG { //测试用例 1 @Test(groups = { "functest" }) public void testCase3() { System.out.println("in test case 3 of OrderofTestExecutionInTestNG"); } //测试用例 2 @Test(groups = { "functest", "checkintest" }) public void testCase4() { System.out.println("in test case 4 of OrderofTestExecutionInTestNG"); } }
testng.xml
这是一个配置文件,用于组织和运行 TestNG 测试用例。当需要执行有限的测试而不是完整的套件时,它非常方便。
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" > <suite name = "Suite1"> <test name = "test1"> <groups> <run> <include name = "functest" /> </run> </groups> <classes> <class name = "NewTestngClass" /> <class name = "OrderofTestExecutionInTestNG" /> </classes> </test> </suite>输出结果
in test case 1 of NewTestngClass in test case 3 of OrderofTestExecutionInTestNG in test case 4 of OrderofTestExecutionInTestNG =============================================== Suite1 Total tests run: 3, Passes: 3, Failures: 0, Skips: 0 ===============================================