如何在命令行中运行 TestNG 中的特定测试组?
组测试是 TestNG 中一个新的创新功能,在 JUnit 框架中不存在。它允许您将方法划分为适当的部分并执行复杂的测试方法分组。
您不仅可以声明属于组的方法,还可以指定包含其他组的组。然后,可以调用 TestNG 并要求它包含一组特定的组(或正则表达式),同时排除另一组。
组测试在您如何划分测试方面提供了最大的灵活性。如果您想连续运行两组不同的测试,则无需重新编译任何内容。
组是在您的 testNG.xml 文件中使用<groups>标签指定的。它可以在<test>或<suite>标签下找到。在<suite>标签中指定的组适用于其下的所有<test>标签。
TestNG 允许从命令行 (cmd) 运行测试套件,但是为此必须满足以下先决条件:
所有依赖的 jar 文件都应该在项目文件夹内可用。它包括testing.jar、jcommander.jar和测试用例中使用的任何其他jar文件。
编译后存储 .class文件的bin或out文件夹的路径。
使用 testNG.xml 运行命令,或者仅针对特定组运行特定类。
在本文中,我们将了解如何从命令行运行特定组的测试。
解决此问题的方法/算法:
步骤 1 - 创建一个测试类,其中包含两个不同的 @Test 方法和 @BeforeMethods,并使用组名称,如以下程序部分所示。
步骤 2 - 编译该类。它将在 IntelliJ 中创建 out 文件夹,在 Eclipse 中创建 bin 文件夹。
步骤 3 - 将所有 jar 文件放在 lib 文件夹中。
步骤 4 - 现在创建如下所示的 testNG.xml。
注意 - testNG.xml 优先于命令行。因此,即使在命令行中提到了组,但在 testNG.xml 中未正确配置,则执行将不会根据组进行。所有执行都将根据 testNG.xml 进行。
步骤 5 - 打开cmd。
步骤 6 - 使用 cd <project_path>导航到项目路径。
步骤 7 - 使用以下命令运行 testNG.xml
java -cp <path of lib>; <path of out or bin folder> org.testng.TestNG <path of testng>/testng.xml
或者,使用以下命令仅执行具有组的特定类:
java -cp <path of lib>; <path of out or bin folder> org.testng.TestNG -testclass <ClassName> -groups <groupname>
示例
以下代码显示了如何从命令行运行特定组的 TestNG 测试:
src/NewTestngClass.java
import org.testng.annotations.*;
import java.lang.reflect.Method;
public class NewTestngClass {
// test case 1
@Test(groups={"test1", "test2"})
public void testCase1() {
System.out.println("in test case 1 of NewTestngClass");
}
// test case 2
@Test(groups={"test2"})
public void testCase2() {
System.out.println("in test case 2 of NewTestngClass");
}
@BeforeMethod(groups={"test1", "test2"})
public void name() {
System.out.println("Before Method");
}
}src/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 = "test1" /> </run> </groups> <classes> <class name = "NewTestngClass" /> </classes> </test> </suite>
运行命令
1. 使用 testng.xml 运行特定组
java -cp C:\Users\********\IdeaProjects\TestNGProject\lib\*;C:\Users\********\IdeaProjects\TestNGProjectct\out\production\TestNGProject org.testng.TestNG src/testng.xml
或者,
java -cp .\lib\*;.\out\production\TestNGProject org.testng.TestNG src/testng.xml
输出
BeforeMethod in test case 1 of NewTestngClass =============================================== Command line suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 ===============================================
2. 不使用 testng.xml 使用类名运行特定组
java -cp .\lib\*;.\out\production\TestNGProjectct org.testng.TestNG -testclass NewTestngClass -groups "test1"
输出
BeforeMethod in test case 1 of NewTestngClass =============================================== Command line suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 ===============================================
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP