如何获取Testng - 如果测试用例具有多个值的数据提供者,则测试方法名称

时间:2018-05-29 18:53:52

标签: 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仅返回付款

testMethodName也应该返回带数据提供者名称的付款。

请帮忙

1 个答案:

答案 0 :(得分:0)

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

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
===============================================