TestNG 如何使用多线程调用测试方法?
TestNG 支持多线程,即 @Test 方法可以并行多次调用。需要从多个线程调用测试方法,以便也需要多次调用。如果我们想在多线程中运行单个 @Test,则没有用。因此,如果需要异步多次运行 @Test 方法,则多线程很有用。
可以通过在 @Test 中使用关键字 **threadPoolSize =** 来实现多线程。但是,要多次调用方法,还需要另一个关键字 **invocationCount =**。结合这两个关键字,我们可以实现多线程。例如,
@Test(threadPoolSize=5, invocationCount = 10)
在此示例中,@Test 方法将从 5 个线程中总共执行 10 次。请注意,从 5 个不同线程中总执行次数为 10。这并不意味着 @Test 将在每个线程中总共运行 50 次或 10 次。它仅仅意味着 5 个线程将总共执行该方法 10 次。
在本文中,我们将说明如何在 TestNG 中实现多线程。
解决此问题的方法/算法 -
步骤 1 - 创建一个名为 NewTestngClass 的 TestNG 类。
步骤 2 - 在类中编写一个 @Test 方法,如程序代码部分所示。添加 **threadPoolSize** 和 **invocationCount**
步骤 3 - 现在创建 testNG.xml 来运行 TestNG 类。
步骤 4 - 运行 testNG.xml 或直接在 IDE 中运行 TestNG 类,或者使用命令行编译并运行它。
在输出中,您可以注意到有 5 个线程并行运行(线程 ID 12 到 16),并且该方法总共运行了 10 次。
示例
对常用的 TestNG 类“NewTestngClass”使用以下代码 -
src/ NewTestngClass.java
import org.testng.ITestContext;
import org.testng.annotations.*;
public class NewTestngClass {
@Test(threadPoolSize = 5, invocationCount = 10)
public void testcase1(ITestContext testContext){
System.out.println("Thread ID: "+Thread.currentThread().getId());
int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount();
System.out.println("Executing count: " + currentCount);
}
}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"> <classes> <class name = "NewTestngClass"/> </classes> </test> </suite>
输出
Thread ID: 12 Thread ID: 13 Thread ID: 16 Thread ID: 14 Executing count: 0 Thread ID: 15 Executing count: 0 Executing count: 0 Executing count: 0 Executing count: 0 Thread ID: 15 Executing count: 5 Thread ID: 12 Executing count: 6 Thread ID: 13 Executing count: 7 Thread ID: 14 Executing count: 8 Thread ID: 15 Executing count: 9 =============================================== Suite1 Total tests run: 10, Passes: 10, Failures: 0, Skips: 0 ===============================================================
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP