如何在 TestNG 中获取方法执行时间?
TestNG 支持原生依赖注入。它允许在方法中声明附加参数。在运行时,TestNG 会自动使用正确的值填充这些参数。以下是一组 TestNG 中的原生依赖项:
- ITestContext
- XmlTest
- Method
- ITestResult
这些依赖项有助于检索测试方法执行所花费的时间。只有在测试执行后才能检索测试方法的执行时间。
如果用户希望在方法执行后获取方法执行时间,则可以使用 @AfterMethod 来检索它。@AfterMethod 支持所有这些原生依赖项。下面提供了这些依赖项的完全访问权限:
| 注解 | ITestContext | XmlTest | Method | ITestResult |
|---|---|---|---|---|
| BeforeSuite | 是 | 否 | 否 | 否 |
| BeforeTest | 是 | 是 | 否 | 否 |
| BeforeGroups | 是 | 是 | 否 | 否 |
| BeforeClass | 是 | 是 | 否 | 否 |
| BeforeMethod | 是 | 是 | 是 | 是 |
| Test | 是 | 否 | 否 | 否 |
| AfterMethod | 是 | 是 | 是 | 是 |
| AfterClass | 是 | 是 | 否 | 否 |
| AfterGroups | 是 | 是 | 否 | 否 |
| AfterTest | 是 | 是 | 否 | 否 |
| AfterSuite | 是 | 否 | 否 | 否 |
在这篇文章中,我们将使用 ITestResult 依赖项来展示如何检索每个测试方法的执行时间。
解决此问题的方法/算法
步骤 1 - 创建一个 TestNG 类 NewTestngClass 并编写 @AfterMethod 方法。
步骤 2 - 在 @AfterMethod 中编写以下代码。
public void name(ITestResult result) {
System.out.println("in aftermethod of NewTestngClass");
long a = result.getEndMillis()-result.getStartMillis();
System.out.println("Time taken to run test is :"+a+" miliiseconds");
}步骤 3 - 在类 NewTestngClass 中编写两个不同的 @Test 方法。
步骤 4 - 现在创建如下所示的 testNG.xml 来运行 TestNG 类。
步骤 5 - 最后,运行 testNG.xml 或直接在 IDE 中运行 TestNG 类,或者使用命令行编译并运行它。
示例
对通用的 TestNG 类 NewTestngClass 使用以下代码:
src/ NewTestngClass.java
import org.testng.ITestResult;
import org.testng.annotations.*;
public class NewTestngClass {
// test case 1
@Test()
public void testCase1() throws InterruptedException {
Thread.sleep(5000);
System.out.println("in test case 1 of NewTestngClass");
}
// test case 2
@Test()
public void testCase2() throws InterruptedException {
Thread.sleep(1000);
System.out.println("in test case 2 of NewTestngClass");
}
@AfterMethod
public void name(ITestResult result) {
System.out.println("in aftermethod of NewTestngClass");
long a = result.getEndMillis()-result.getStartMillis();
System.out.println("Time taken to run test is :"+a+" miliiseconds");
}
}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>输出
in test case 1 of NewTestngClass in aftermethod of NewTestngClass Time taken to run test is :5011 miliiseconds in test case 2 of NewTestngClass in aftermethod of NewTestngClass Time taken to run test is :1008 miliiseconds =============================================== Suite1 Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 ===============================================
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP