如何在 TestNG 测试用例中指定类级组?
组测试是 TestNG 中一个新的创新功能,在 JUnit 框架中不存在。它允许您将方法划分为适当的部分,并执行测试方法的复杂分组。
您不仅可以声明属于组的方法,还可以指定包含其他组的组。然后,可以调用 TestNG 并要求其包含一组特定的组(或正则表达式),同时排除另一组。
组测试在您如何划分测试方面提供了最大的灵活性,并且如果您想连续运行两组不同的测试,则不需要重新编译任何内容。即使组也可以在类级别提及,因此所有测试都将执行属于同一组的类的测试。
组在您的 testng.xml 文件中使用 <groups> 标签指定。它可以在 <test> 或 <suite> 标签下找到。在 <suite> 标签中指定的组适用于下面的所有 <test> 标签。
现在,让我们举一个例子来看看组测试是如何工作的。
解决此问题的方法/算法
步骤 1:创建 TestNG 类 - NewTestngClass
步骤 2:在类中编写 3 个不同的 @Test 方法 - NewTestngClass
步骤 3:按照代码文件中提到的方法,为每个 @Test 添加组标记。
步骤 4:在类名前面,类顶部写上组名,如程序部分所示。
步骤 5:现在创建如下所示的 testNG.xml 以执行组名为 GlobalGroup 的 @Test。它是类级组名。
步骤 6:现在,运行 testNG.xml 或直接在 IDE 中运行 TestNG 类,或者使用命令行进行编译和运行。
步骤 7:根据给定的配置,它将执行 NewTestngClass 的所有 3 个测试用例。
示例
以下代码展示了如何运行测试组
src/ NewTestngClass.java
import org.testng.annotations.Test;
@Test(groups = { "GlobalGroup" })
public class NewTestngClass {
@Test(groups = { "unit", "integration" })
public void testCase1() {
System.out.println("in test case 1 of NewTestngClass");
}
@Test(groups = { "integration" })
public void testCase2() {
System.out.println("in test case 2 of NewTestngClass");
}
@Test(groups = { "unit" })
public void testCase3() {
System.out.println("in test case 3 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">
<test name = "test1">
<groups>
<run>
<include name = "GlobalGroup" />
</run>
</groups>
<classes>
<class name = "NewTestngClass" />
</classes>
</test>
</suite>
输出
in test case 1 of NewTestngClass
in test case 2 of NewTestngClass
in test case 3 of NewTestngClass
===== Invoked methods
newTest.testCase1()[pri:0, instance:newTest@7946e1f4]
newTest.testCase2()[pri:0, instance:newTest@7946e1f4]
newTest.testCase3()[pri:0, instance:newTest@7946e1f4]
=====
===============================================
suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP