首页 > 解决方案 > 如果测试用例具有具有多个值的数据提供者,如何获取 Testng - 测试方法名称

问题描述

@DataProvider(name = "Payment")
public static Object[][] Payment() {
        return new Object[][] {
                { "TC_001", "Payment 1" }, 
                { "TC_002", "Payment 2" }
        };
    }

@Test(enabled = true, dataProvider = "Payment")
public void Payment(String testCaseNumber, String testDesc) throws Exception { 
}

@AfterMethod
public void tearDown(ITestResult result) {
    testMethodName = result.getMethod().getMethodName();
}

这里 testMethodName 只返回 Payment

testMethodName 还应该返回 Payment with Data 提供者名称。

请帮忙

标签: testng

解决方案


这是一个示例,展示了如何提取这些值。

import java.lang.reflect.Method;
import java.util.Arrays;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestClassSample {

  @Test(dataProvider = "dp")
  public void testMethod(int i) {}

  @DataProvider(name = "dp")
  public Object[][] getData() {
    return new Object[][] {{1}, {2}};
  }

  @AfterMethod
  public void afterMethod(ITestResult result) {
    Object[] parameters = result.getParameters();
    Method method = result.getMethod().getConstructorOrMethod().getMethod();
    String msg = "";
    Test test = method.getAnnotation(Test.class);
    if (test == null) {
      return;
    }
    msg += "The @Test method [" + method.getName() + "] ";
    String dataProviderName = test.dataProvider();
    Class clazz = test.dataProviderClass();
    if (!dataProviderName.trim().isEmpty()) {
      msg += " had its data provider name as [" + dataProviderName + "] ";
      if (clazz != Object.class) {
        msg += " and class as [" + clazz.getCanonicalName() + "] ";
      }
    }
    if (parameters != null) {
      msg += " and had parameters as " + Arrays.toString(parameters);
    }
    System.err.println(msg);
  }
}

这是输出

The @Test method [testMethod]  had its data provider name as [dp]  and had parameters as [1]
The @Test method [testMethod]  had its data provider name as [dp]  and had parameters as [2]

===============================================
Default Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

推荐阅读