如何获取在 TestNG 拆卸方法中运行的测试方法的名称?

testngrest assureddynamic programming更新于 2025/6/2 8:37:17

TestNG 支持原生依赖注入。它允许在方法中声明额外的参数。在运行时,TestNG 会自动用正确的值填充这些参数。以下是 TestNG 中的一组原生依赖项:

  • ITestContext
  • XmlTest
  • Method
  • ITestResult

这些依赖项有助于检索测试方法的名称。测试方法的名称可以在测试执行之前或之后获取。

  • 如果用户想要在测试方法执行之前获取其名称,可以使用 @BeforeMethod 进行获取。

  • 另一方面,如果用户想要知道刚刚执行的是哪个测试方法,可以使用 @AfterMethod。实际代码可以使用这两种方法中的任意一种来获取测试方法的名称。

@BeforeMethod@AfterMethod 支持所有这些原生依赖项。这些依赖项的完整访问权限如下所示。 −

AnnotationITestContextXmlTestMethodITestResult
BeforeSuiteYesNoNoNo
BeforeTestYesYesNoNo
BeforeGroupsYesYesNoNo
BeforeClassYesYesNoNo
BeforeMethodYesYesYesYes
TestYesNoNoNo
AfterMethodYesYesYesYes
AfterClassYesYesNoNo
AfterGroupsYesYesNoNo
AfterTestYesYesNoNo
AfterSuiteYesNoNoNo

在本文中,我们将使用方法依赖项来演示如何检索测试方法的名称。但是,这些依赖项中的任何一个都可以用于 @BeforeMethod@AfterMethod。唯一的变化是在 import 部分,应根据所使用的原生依赖项导入相应的库。

假设用户想要在测试方法执行后检索其名称。在这种情况下,代码将写入 @AfterMethod 中以检索测试方法的名称。由于 @AfterMethod 每次在 @Test 方法之后执行,因此测试方法的名称将在执行后打印出来。

解决此问题的方法/算法

  • 步骤 1 −创建一个 TestNG 类 NewTestngClass 并编写 @AfterMethod 方法

  • 步骤 2 − 在 @AfterMethod 中编写以下代码

public void tearDown(Method method) {
    System.out.println("Test name: " + method.getName());
}

注意 − 除了参数 Method 之外,还可以使用其余三个原生依赖项中的任何一个。例如,ITestContextXmlTestITestResult

  • 步骤 3 −在 NewTestngClass 类中编写两个不同的 @Test 方法。

  • 步骤 4 − 按照如下所示创建 testNG.xml 以运行 TestNG 类。

  • 步骤 5 − 最后,运行 testNG.xml 或直接在 IDE 中运行 testNG 类,或使用命令行编译并运行它。

示例

Use the following code for the common TestNG class, NewTestngClass

src/ NewTestngClass.java

import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
public class NewTestngClass {
   @Test
   public void testCase1() {
      System.out.println("in test case 1 of NewTestngClass");
   }
   @Test
   public void testCase2() {
      System.out.println("in test case 2 of NewTestngClass");
   }
   @AfterMethod
   public void tearDown(Method method) {
      System.out.println("Test name: " + method.getName());
   }
}

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
Test name: testCase1
in test case 2 of NewTestngClass
Test name: testCase2
===============================================
Suite1
Total tests run: 2, Passes: 2, Failures: 0, Skips: 0
===============================================

相关文章